Send Authentication header with fetch or axios - javascript

How to send authentication header with fetch or axios ?
I have tried to do it but it on my client side haven't any header with Authentification value.
Here is my code example.
let myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Access-Control-Allow-Origin", "*");
let req = {
method: "GET",
headers: myHeaders,
mode: "no-cors",
credentials: "same-origin",
}
fetch('http://localhost:5000/secret', req)
.then(res => console.log(res))
.catch(err => console.log(err))
And I tried check it on my node.js code.
router.route("/").get(passportJWT, SecretController.secret);

For two origins to be considered "the same", they must share:
Scheme (e.g. https)
Hostname
Port
You are making a request from http://localhost:3000 to http://localhost:5000 so are making a cross-origin request.
credentials: "same-origin"
… but you've restricted credentials (like Authorization) to same-origin requests.
mode: "no-cors",
To send credentials with a cross-origin request, you must have permission via CORS.
You must not set no-cors.
You need
mode: "cors",
credentials: "include"

Related

fetch() api does not send headers and body in "no-cors" mode?

I am sending POST request like this from browser and it is a cross platform request:
var reg_data = {"name": "John"};
fetch(url, {
method: 'POST',
mode: 'no-cors',
headers: new Headers({
'Content-Type': 'application/json',
'token': 'value'
}),
body: JSON.stringify(reg_data)
})
By the time the request reaches my back-end it does not contain token nor body.
Following is my backend ruby code -
before_action :cors_preflight_check
def cors_preflight_check
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Accept, Content-Type, token'
end
I checked some articles it says it happens as the mode is set to "no-cors" the headers and body is restricted. It works fine with postman, but fails with browser. How do I solve this issue as I want to serve a cross platform request and also access the request headers and body?

Cant enable CORS on the server side NodeJS

I can't enable CORS on the server-side. My frontend and backend servers have different ports. Here is how server-side is implemented:
http
.createServer(function (req, res) {
// .. Here you can create your data response in a JSON format
// const { headers, method, url } = req;
// let body = [];
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// const responseBody = { headers, method, url, body: JSON.stringify(data) };
response.write('{asd: 123}'); // Write out the default response
res.end(); //end the response
})
.listen(port);
And I call the fetch function from the frontend-side like this one:
fetch('http://localhost:3035', {
method: 'POST',
mode: 'same-origin', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(line), // body data type must match "Content-Type" header
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
But still getting errors:
Security Error: Content at http://localhost:3030/ may not load data from http://localhost:3035/.
TypeError: "NetworkError when attempting to fetch resource."
You explicitly disallowed CORS on the client side by setting mode: 'same-origin' instead of the default mode: 'cors'.
To quote the docs:
same-origin — If a request is made to another origin with this mode set, the result is simply an error. You could use this to ensure that a request is always being made to your origin.
Since http://localhost:3035/ is another origin than http://localhost:3030/, the result is, exactly as designed, "simply an error".
Set it to mode: 'cors' or remove mode entirely since cors is the default anyway.
On a side note, Access-Control-Request-Method is a request header in the preflight request, not a response header. You should remove it.
As mentioned in the comments: For a credentialed request to work, you cannot use an allowed origin of *. If you don't want to hardcode the expected origin at this point though, you can avoid this problem by always returning the origin that the current request comes from, using res.setHeader('Access-Control-Allow-Origin', req.headers.origin).

Not sending correct header in netuno

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());

fetch request not sending cookies to PHP server

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 :-)

Can not do cross domain REST API Call from localhost [duplicate]

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

Categories

Resources