react fetch header not set - reactjs

I am facing a problem. And the solutions that are accepted by the others, those don't work for me./
I have:
return await fetch(url, {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
},
body: JSON.stringify(bodyObject)
});
But, it seems like no header is set at all.
Cors-header is set, adding mode:'cors' makes no difference.
Am I missing something?
the request:
Accept is empty and Content-Type nor x-test are nowhere to be found.
..
Edit
..
If i need to create new question, do tell me.
New request
So I see that the header is set - thanks to liminal18!-. However, now i want to authorize to an AD.
so now I got:
async callUrl(url, httpMethod, bodyObject) {
try {
var requestObj = {
method: httpMethod,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'x-test':'try me',
'Authorization': 'Basic Uk11bGxlc....'
}
};
if (bodyObject !== undefined){
requestObj.body = JSON.stringify(bodyObject);
}
return await fetch(url, requestObj);
} catch(error){
console.error(error);
}
}
But still get an 401.
I know this is not the clean solution for logging in, but just testing..

Are you sure the request you captured is the correct request?
if you're using CORS there is an OPTIONS post to get the cors allowed methods before react will post/put which might be what you are looking at and not the actual post or put you intended. Where are the CORS headers set?

Related

React native - FETCH - Authorization header not working

I made a server query via an app developed using react-native. I used fetch API and it turns out any query with authorization header not working. POST and GET method REQUESTS that don't expect Authorization headers at the server side works well. Some Queries at the server side are protected with authorization and when I make such queries including authorization header, I always get '401:unauthorized' error.
But such queries works well with POSTMAN. Any suggestions here would be of great help.
getThingsApi() {
let uri = "https://example.com/things/";
let req = {
method: "GET",
credentials: "include",
//mode: "no-cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
//'Access-Control-Request-Method': 'GET',
//'Access-Control-Request-Headers': 'origin, x-requested-with',
'Origin': '',
'Host':'example.com',
'authorization': 'Basic '+Base64.btoa('aaa:bbb'),
'Cache-Control': 'no-cache'
}
};
fetch(uri, req)
.then(response => response.json())
.then(responseJson => {
console.log("ResponseAxis::" + JSON.stringify(responseJson));
console.log("ResponseAxis::" + JSON.stringify(responseJson));
alert("ResponseAxis::" +JSON.stringify(responseJson));
})
.catch(error => {
console.log("Error::" + JSON.stringify(error));
});
}
Issue is fixed. We used Fetch API and fetch Api converts all headers into lower-case(eg: authorization) and the server side expects upper-case starting letter(eg: Authorization). After changing the server side code to be case-insensitive, everything works fine.

Convert this CURL Command to Javascript fetch()

I have a problem, I'm trying to access an API via javascript fetch().
In their documentation, they only have the curl guide
curl https://test.com/form/{form_id}/data \
-u apikey:'some-key'
Can you guys help me convert it to javascript fetch?
I tested the code below but the browser console says error 401 now I don't think I did put the apikey on the right location.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
apikey : 'some-ley',
'Content-Type': 'application/json'
}
})
Thanks in advance. :)
I think what is failing there is the type of header you are sending in fetch.
The -u option in curl translates to the "authorization" header in fetch. So it would be something like this.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'authorization' : 'Basic apikey:some-key',
'Content-Type': 'application/json'
}
})
Although probably you would need to base64 encode the apikey:some-key portion before sending it.
Try this format:
fetch("https://test.com/form/{form_id}/data", {
headers: {
Authorization: "apikey ABCDEFGHIJK.."
}
})
Try these awesome online cURL converters!
Here is the output when you paste the cURL command and select the Javascript target:
fetch('https://test.com/form/371489/data', {
headers: {
'Authorization': 'Basic ' + btoa('apikey:some-key')
}
});

What is the best way to enable CORS in React Application?

There are different ways to make a REST call in react-
e.g
axios.post('link', JSON.stringify(data1),
{
headers: {"content-type" : "application/json", "Access-Control-Allow-Origin" : "*"}})
.then(response => {
console.log("res:", response)
})
.catch(err =>{
console.log(err)
})
}
OR
fetch('http://localhost:8080/feedbacks/addfeedback', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
body:body
What is the most effiecient way to enable CORS.
Is there any other way that I can do this either in frontend or backend?
It depends on what HTTP library you are using.
See What is difference between Axios and Fetch?.
I usually use Axios, next what i do is creating a global instance and configuring Axios once.
export const api = axios.create({
baseURL: '_URL_',
timeout: 1000,
withCredentials: false,
responseType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' // whatever you want
}
});
// You can add common headers later
api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Also i'm enabling CORS on my server side application.
Thanks to #henrik123 for good explanation:
The browser is going to see that some Javascript request has tried to initiate a request to a different domain, subdomain or port than what the browsers is currently at. If any of these things are different, the CORS kicks in. Doesn't matter if you use Axios, Fetch or any other other library

How to pass JsonWebToken(JWT) through AngularJS

I created a Django RESTful API with JWT as authentication method, but unable to pass the token as headers using angularJS.
I think there is no error on my API, since I used the token I acquired by this script and tested it in Postman:
my JWT token authentication script is here:
// Uses http.get() to load data from a single API endpoint
list() {
return this.http.get('api/', this.getHttpOptions());
}
// helper function to build the HTTP headers
getHttpOptions() {
return {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
})
};
}
I tried using http.get() here. Thanks in advance!
the error will be like:
401 (Unauthorized)
Try this:
list() {
return this.http.get('api/', { this.getHttpOptions() });
}
getHttpOptions() {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token
});
return headers;
}
Same issue on JWT for CakePHP3, and follow header slove it, may it is helpful.
this.http.get('api/', { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'JWT ' + this._userService.token,
'Authenticationtoken': 'JWT ' + this._userService.token
}) });
Thanks guys,
I found the problem is about CORS, My solutions are here, there are two approaches to solve this problem, one is add 'Access-Control-Allow-Origin': '*' to your http request, sometimes you need add more. Another answer is add CORS_ORIGIN_WHITELIST = 'localhost:4200', in your backend.
https://www.youtube.com/watch?v=OIbndrrUYiY

Sending POST request weird issue

I'm quite new with ANGULAR and web development in general and I'm currently working on a web tool. Now I want this tool to send a POST request to a web service but Im encountering a weird bug. Now I have below code in my javascript:
var data_info = { test_id: 'TEST', model_id: 'TEST:TEST_ID' };
//data_info = JSON.stringify(data_info);
var request_json = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
data: data_info,
cache: false,
};
console.log(request_json);
$http(request_json).then(function successCallback(response) {
// response code here
}
Now this code currently doesn't pass the preflight request check and is always returning a 405. But if I change the line data: data_info in the request JSON into a new key let's say body: data_info it now successfully sends the request and I can confirm that the service is receiving it. I'm not sure what's the issue here and can't figure it out.
change your header to :
headers : {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
Please try

Resources