Using the Nextjs getServerSideProps function I make a fetch request to my API. My API checks origin headers for CORS but gets the origin header as undefined. Why is this happening and is there a way around this?
I get origin headers while making fetch requests normally from the browser in Next. This issue only occurs when the request is made to the API via the server from Nextjs getServerSideProps.
What I did was adding the Origin parameter to the header object in the fetch request and adding the url from the .env file to easily change it for production.
//Create fetch's options
const options = {
mode: 'cors',
method: 'GET',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Origin: `${process.env.NEXT_PUBLIC_FRONT_URL}`,
},
};
//Fetch data from the API
const res = await fetch('changeForYouURL', options);
I have a backend developed in netuno with api in java, and I want to send a pdf, I have no errors sending an excel, but for some reason I'm not getting it with pdf, my frontend is with react and redux.
The pdf is working when tested in postman (and yes, I know that in postman there are no cors problems),
In the browser if I send a corrupted pdf it is sent to the frontend but if the pdf has the right data it no longer passes in the cors.
I've already put the settings on the server side to receive the correct headers
_header.response.set('Access-Control-Allow-Origin', '*')
_header.response.set('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
_header.response.set('Access-Control-Allow-Headers', 'Content-Type, Expires, Cache-Control, must-revalidate, post-check=0, pre-check=0, Pragma')
_header.response.set('Access-Control-Allow-Credentials', 'true')
On the java side the pdf is going with the following headers
HttpServletResponse res = proteu.getServletResponse();
res.setHeader("Expires", "0");
res.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
res.setHeader("Pragma", "public");
res.setContentType("application/pdf");
res.setContentLength(baos.size());
OutputStream out = res.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
My fetch call is like this right now:
import fetch from "cross-fetch";
const FileSaver = require("file-saver");
const qs = require("qs");
fetch("myEndPoint", {
headers: {
accept: "application/pdf",
"content-type": "application/x-www-form-urlencoded"
},
referrerPolicy: "no-referrer-when-downgrade",
method: "POST",
mode: "no-cors",
body: qs.stringify({
...action.value
})
})
.then(resp => resp.blob())
.then(blob =>
FileSaver.saveAs(
blob,
"myPdf" +
new Date(Date.now())
.toLocaleString()
.replace(new RegExp("/", "g"), "")
.split(",")[0] +
".pdf"
)
);
when I execute the code in the browser, that's the way it is:
fetch("myEndPoint", {
credentials: "omit",
headers: { accept: "application/pdf", "content-type": "application/x-www-form-urlencoded", "sec-fetch-mode": "cors" },
referrer: "http://localhost:3000/foo",
referrerPolicy: "no-referrer-when-downgrade",
body:
"myData=foo",
method: "POST",
mode: "cors"
});
And I get the following error code:
Access to fetch at 'myEndPoint' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
which is strange, considering that all other calls work except this one, and the only difference is the type of document I get.
I have no error on the backend side.
why is chrome editing the mode: "no-cors" for "mode: "cors" ??
if I try to use "sec-fetch-mode: no-cors" in the fetch call header chrome answers:
Refused to set unsafe header "sec-fetch-mode"
The problem was in HttpServletResponse, when you use this on the netuno, it rewrites the header options, so I wasn't sending my previously configured settings, so the correct way to do this is as follows:
BaseService service = new BaseService(proteu, hili);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//my pdf code
service.getHeader().contentTypePDF();
service.getHeader().noCache();
service.getOut().write(baos.toByteArray());
I am having a weird problem where when I make a fetch request from the client in development it is not sending the cookies to my server (legacy server that does not run on localhost).
Here is my code for the fetch request:
get( url ) {
return fetch(`${API_URL}${url}`, {
method: 'GET',
headers: headers(),
credentials: 'include'
}).then( parseResponse );
},
Headers is a function that returns the following object:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
'mobile': 'false'
}
Here are the CORS headers I have set on the server (Access-Control-Allow-Origin is dynamic because fetch has issues with *)
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: mobile, Content-Type
Access-Control-Allow-Origin: http://localhost:3000
If I print out $_COOKIE I get back an empty array and when I look at the request I get Provisional headers are shown with no cookies.
Any ideas where I messed up?
Thanks In Advance :-)
I am receiving an error when attempting to redirect to github api for user authorization. The error says that "Reponse to preflight request doesn't pass access control check", it references no "Access-Control-Allow_origin" header is present, however I have it added in my fetch request and I have it set to wildcard.
fetch('https://github.com/login/oauth/authorize?client_id=00000&scope=repo', {
mode: 'cors',
credentials: 'include',
headers: {
'Access-Control-Allow-Origin': '*',
'Accept': 'application/json',
}
})
I can click in the "Network" tab and double click the request and it takes me to github to authorize my application. Not sure what else I can be missing?
This question already has an answer here:
Enable CORS in JIRA REST API
(1 answer)
Closed 4 years ago.
I am trying to do login using REST API provided by JIRA in REACT.
But I am getting error like
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8085' is therefore not allowed access. The response had HTTP status code 403.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Below is my code which I am testing to do sign on.
fetch("https://jira.company.com/rest/auth/latest/session",{
method:'POST',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*"
},
body:
JSON.stringify({
username:"username",
password : "password"})
}).then(result => console.log(result));
I have also tried with below parameter but it result with same error.
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
I have also looked into documentation for JIRA API but can not find anything for cross domain request access.
Looking for help to do API call across domain.
Try by setting mode: 'cors'
fetch("https://jira.company.com/rest/auth/latest/session", {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
mode: 'cors',
body: JSON.stringify({
username: "username",
password: "password"
})
}).then(function(resp) {
return resp.json();
}).then(function(data) {
console.log(data)
});
Note:In the demo you may see 404 which mean not found because it is not sending username & password