can't set header with fetch - react-native

I set a header for post a request with application/x-www-form-urlencoded form body;
here's my code
var headers = new Headers();
headers.append('Content-Type','application/x-www-form-urlencoded');
fetch(url, {
method: "POST",
mode:"cors",
header:headers,
body: qs.stringify(params)
})
But Content-type changed autoly in the request
Content-Type text/plain;charset=UTF-8
So that I can't receive this request params correctly.
Any one meet that?

CORS only allows a subset of content types. I lost lots of hours to this one. :)
See this answer. Even though application/x-www-form-urlencoded could be possible in a CORS request, I think it's very likely that your header is being overwritten by setting mode: 'cors' in your fetch call.

Related

Request header field authorization

I am trying to create "UUID" form this Api call
I am using axios and vue.js. Here's my source code.
generateUUID() {
// console.log("call generate uuid");
const headers = {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*'
}
axios.get('https://www.uuidtools.com/api/generate/v1', {
headers: headers
}).then(response => console.log(response))
},
But unfortunately I am getting
Access to XMLHttpRequest at 'https://www.uuidtools.com/api/generate/v1' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried searching google and followed many answers already to that question but got nothing.
Problem(s)
Access-Control-Allow-Headers and Access-Control-Allow-Origin are response headers, not request headers. Specifying them in a request is more than useless; it's actually counterproductive, here.
Why would you specify a content type for a GET request? GET requests are not supposed to have a body:
A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.
According to my tests, the resource that you're requesting (https://www.uuidtools.com/api/generate/v1) appears to be CORS-aware but expects only simple requests, not preflight requests. And because your request contains headers that are not CORS-safelisted, it gets preflighted by your browser, and the preflight access-control check fails.
Solution
Just send a simple GET request (without adding any headers):
fetch('https://www.uuidtools.com/api/generate/v1')
.then(r => r.json())
.then(arr => arr[0])
.then(console.log)
Console output
No CORS error, then:
]

How to use multiple Content-type in headers of Http Post request

I have this code where there are multiple Content-type keys is used in this POST request.When this request is run I always get an error that a duplicate key is used.I want to know how I can use multiple Content-type in one Content-type key.The header of the request looks like below:-
headers: {
'Content-Type':'application/json,
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data; charset=utf-8; boundary=' + Math.random().toString().substr(2)
}
You can’t. Are you sending JSON or Form-Data? It can’t be both so has to be one or the other.

Sending axios get request with authorization header

I have tried to send axios get request using vue.js and it worked just fine when there was no need to send headers. However, when it was required to send an authorization jwt, i was getting CORS error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." I don't know why is this problem occurring since there is Access-Control-Allow-Origin: '*' header in the response. My code is the following:
axios.get(url, {
headers: {
'Authorization': 'Bearer TOKEN'
}
})
.then(function (response) {
console.log(response.data)
})
The weirdest thing is when I use querystring.stringify or JSON.stringify on the header, I don't get the error 403(forbidden), but just an error 401 - Unauthorized. I tried with variable and with the token itself and it didn't work.
I tried to send a post request in order to get a web token with required data - username an password and it worked. I was able to get the token.
I made a whole bunch of research the last two days on this and I found different kind of request structure and configs which I tried all of them, but none were efficient. Is there a way to check if the request is being send with the header? Is something else the problem? If someone can help, I would appreciate. Thanks.
I think you should add this code to the bootstrap.js (or where the axios is defined):
window.axios = require('axios'); // I think its already added
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
You didn't mention, but I guess you use laravel, or other framework, what is protected from csrf attack, thats why you need to add the generated token to your ajax request header.

How to remove Accept-Encoding header from the header part in $http.get angularjs

I want to remove access-encoding header from $http.get request. Tried via following, but not any luck.
delete $httpProvider.defaults.headers.common['Accept-Encoding'];
$http({ method: 'GET', url: apiUrl, data: '', headers: { 'Content-Type': 'application/json', 'accept-encoding': null } });
Please share your thoughts.
For the very same purpose, I am following this fiddle,
http://fiddle.jshell.net/X2p7r/344/
also as per documentation of AngularJS
To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g.
$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }
I am able to modify 'Accept' and 'Content-Type' headers but not able to do same with Accept-Encoding, doesn't change no matter what I try it remains same.
Thanks in Advance for any help.
Edit:https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
I tried to set Accept-Encoding according to the ways mention in above link.

How to set Content-Type header in a http get response using C#'s HttpClient?

I am having problems in retrieving the contents of a http get request in the proper charset.
I tried several pieces of code, such as the following:
HttpClient h = new HttpClient();
//Content-Type: text/html; charset=UTF-8
//p.s. contents are in hebrew.
var resp = h.GetAsync("http://www.wnf.co.il");
var content = resp.Result.Content;
//remove the default Content-Type header
content.Headers.Remove("Content-Type");
content.Headers.Add("Content-Type", "text/html; charset=utf-8");
var res = content.ReadAsStringAsync();
var s = res.Result;
Console.WriteLine(s);
which still does not help, I still get the content in wrong encoding.
This post clarifies that setting the header's request headers charset will not help, it's the response's one that needs to be set. (Besides, you will get an error in trying to add
header "Content-Type" to a request Header.)
But I still could not end up with working retrieval of the content in the proper charset (utf-8).
What am I missing ?
I have been doing similar stuff with hebrew sites for a while, in comparing the response's header in Fiddler from this site and others where I do not have this problem - the only difference I see is indeed this Content-Type header in the response.
The issue is probably due to this bug:
https://connect.microsoft.com/VisualStudio/feedback/details/790174/system-net-http-httpcontent-readasstringasync-does-not-handle-imperfect-content-type-headers
The work-around is to get the response as a byte array and encode it yourself:
var bytes = await content.ReadAsByteArrayAsync();
var s = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
As a side-note, is there a reason you're using .Result instead of await? You are blocking the current thread unnecessarily and setting yourself up for deadlocks.