Comments (49)
@npassaro ok, I got it - the following works. Followed the example on MDN:
var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
fetch('/contact-form', {
method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default',
body: JSON.stringify(fields)
}).then(() => {
dispatch(contactFormSubmitSuccess());
});
from isomorphic-fetch.
I have the exact same problem, did anyone know a fix for this?
From what I've observed, the problem seems to come from the Content-Type
header not being set.
const request = new Request(`${config.apiUrl}/jobs`, {
method: 'POST',
mode: 'no-cors',
redirect: 'follow',
body: JSON.stringify({ job }),
headers: new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
})
});
console.log(request.headers.getAll('Content-Type'));
On the console I only only see: ["text/plain;charset=UTF-8"]
from isomorphic-fetch.
@Roconda it's more likely to be an issue with GitHub's fetch polyfill, which this library pulls in. (Look at the code of this library — it's almost nothing)
Sorry but I'm going to close this again — could not reproduce.
from isomorphic-fetch.
are you using the right body parser? @wallacyyy
https://github.com/expressjs/body-parser
from isomorphic-fetch.
There wouldn't be any data in the headers would there?
The Content-Length:
being 28
suggests that some data is being posted, try running:-
JSON.stringify({
email: 'foo',
pass: 'bar'
}).length
…to see that results in 28
.
I think it's working. Try double checking your server side implementation.
from isomorphic-fetch.
Hi, no-cors
mode makes content-type header immutable. Make sure you have mode: 'cors'
or the default. Hope it helps.
from isomorphic-fetch.
@wallacyyy I couldn't figure out why it wasn't working. I'm now using https://github.com/visionmedia/superagent and it works like a charm. I'm reopening this ticket since it's still an issue.
from isomorphic-fetch.
Just used the 'Content-Type' sol and it solved my problem!
from isomorphic-fetch.
Unfortunately my back end is a rails server. The problem that I'm facing is that if I make a request using fetch the body not show up basically. The same request with curl works fine. Really weird.
I tried put explicit headers for json and still it don't work.
from isomorphic-fetch.
When you do mode: cors, be sure to add something like kcors or koa-cors on
your node server (if applicable) to get cross origin calls working—I spent
most of yesterday trying to figure that one out ;)
On Wed, May 11, 2016 at 4:38 AM Nuno Passaro [email protected]
wrote:
Hi, no-cors mode makes content-type header immutable. Make sure you have mode:
'cors' or the default. Hope it helps.—
You are receiving this because you commented.
Reply to this email directly or view it on GitHub
#34 (comment)
from isomorphic-fetch.
Having this issue as well with a simple node server. I can't get the JSON I'm trying to POST
...
Client:
fetch('contact-form', {
method: 'POST',
body: {
name: 'Dan'
}
});
Node (using express 4.x):
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: false
}));
app.post('/contact-form', (req, res) => {
console.log(req);
})
When I call the fetch
, I can see the console log out the req
obect into the terminal but there is no name
property on the body
property (it's empty)
from isomorphic-fetch.
hope this helps:
headers: {'Content-Type':'application/x-www-form-urlencoded'},
from isomorphic-fetch.
@dwilt you have to send the body as JSON string. Do:
body: JSON.stringify({ name: 'Dan'})
from isomorphic-fetch.
@rbriski, its all about security. Prevent untrusted domains from sending requests with a given payload type that may change data on the server:
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.
You can see a detailed explanation here:
CORS, modern browsers will prevent you from sending requests from a domain to a server in another domain, unless the server allows it. Typically through OPTIONS
from isomorphic-fetch.
@dwilt your case is wierd... 😄 But now that I'm looking more closely to your code I see that you are making a request to the same server where the Front End is rendered/served, am I correct? Try this in the Header:
mode: "same-origin"
(Mozilla Foundation - Request.mode)
Moreover, can you see you request in inspect > Network
? Does your request appear exiting the browser with the expected body?
from isomorphic-fetch.
@Jaikant i was calling it client side but I wasn't getting any errors. I just wasn't receiving the params I was passing to the server. The solution was to use the exact example on MDN. Specifically the Headers, mode and cache properties on the options object I passed seemed to fix it
from isomorphic-fetch.
I had the same issue because of 'preflighting' -
The OPTION request shows as 'XHR' and the POST shows as 'Other'
from isomorphic-fetch.
nothing above made it work from my side, switching to another library...
its simple post request and if its this much pain.... idk...
from isomorphic-fetch.
@radha-kotecha it seem that you are sending JSON with the wrong Content-Type
. Where you have:
"Content-Type": "application/x-www-form-urlencoded"
It should read:
"Content-Type": "application/json"
from isomorphic-fetch.
I'm having the same issue, how did you solve it ? @Roconda
from isomorphic-fetch.
@Roconda could you include your CURL statement? This might lead to a bit more insight as to the issue... also, if you're relying on session cookies, auth, etc, you may also need to use credentials: 'include'
in your options...
from isomorphic-fetch.
By the way there is a bug in Chromium which causes the request body to not be displayed in the Network tab in dev tools: https://code.google.com/p/chromium/issues/detail?id=457484
Try to make the request in FF and see if the body is there.
from isomorphic-fetch.
I'm also having this issue today.
from isomorphic-fetch.
Yea, it does not send post request to the server. Same problem...
from isomorphic-fetch.
My workaround was to tell koa's bodyParser that everything coming in was
JSON using its "detectJSON" option
On Tue, May 10, 2016 at 8:05 PM Ömer Ufuk Efendioğlu <
[email protected]> wrote:
Yea, it does not send post request to the server. Same problem...
—
You are receiving this because you commented.
Reply to this email directly or view it on GitHub
#34 (comment)
from isomorphic-fetch.
@npassaro tried that - still doesn't work.
from isomorphic-fetch.
FYI, similar to @Roconda, I tried it with https://github.com/visionmedia/superagent and it worked like a charm but I'd prefer to use fetch
as I think the syntax is nicer:
request
.post('contact-form')
.send({
name: 'Dan'
})
.end(function(err, res){
console.log(res);
});
from isomorphic-fetch.
@dwilt What's the content-type
header value sent in the post?
from isomorphic-fetch.
@npassaro application/json; charset=utf-8
fetch('contact-form', {
method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default',
body: fields
})
.then(res => {
var contentType = res.headers.get("content-type");
// contentType === 'application/json; charset=utf-8'
})
from isomorphic-fetch.
I'm having the same issue but I'm using mode: 'no-cors'
. @npassaro: Why does that make the Content-type
immutable? I don't have the option of using CORS.
from isomorphic-fetch.
@dwilt awesome! Glad I could help!
from isomorphic-fetch.
@npassaro you're awesome - thank you for your help.
from isomorphic-fetch.
@dwilt was the above issue on the server side or client side?
from isomorphic-fetch.
Tried the solutions here and still not posting json body !
fetch('/main/newuser',{
method:'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({username:'test',password:'test'})
}).then((response)=>{
if(response.status >= 200 && response.status < 300){
return response;
}else{
var error = new Error(response.statusText);
error.response = response;
throw error;
}
}).then((response)=>{
return response.json();
}).then((data)=>{
/* Process data */
}).catch((error)=>{
/* Catch Error */
});
from isomorphic-fetch.
I had this issue as well using node-fetch... With my setup, it was passing Content-Type correctly; however, case mattered. I had to use "content-type" not "Content-Type".
from isomorphic-fetch.
thank you for your help.
from isomorphic-fetch.
body = JSON.stringify(body)
worked for me as well!
from isomorphic-fetch.
Hi All,
I had the same problem, no json was being sent thru to server, the code looked as follows:
return fetch(`${API_URL}auth/signin`,{
method: 'POST',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(payload)
}).then(this.checkStatus)
.then(this.parseJson)
.catch(this.serverError)
The error i was getting with above code was:
Fetch API cannot load http://localhost:3001/auth/signin. Response for preflight has invalid HTTP status code 500
THE FIX
Simply add mode: 'no-cors'
Fixed code:
return fetch(`${API_URL}auth/signin`,{
method: 'POST',
headers: {
'Content-Type':'application/json',
},
mode: 'no-cors',
body: JSON.stringify(payload)
}).then(this.checkStatus)
.then(this.parseJson)
.catch(this.serverError)
from isomorphic-fetch.
@pkrall520 That's a bug in whatever server implementation you are using... HTTP header names are supposed to be case-insensitive.
@zulucoda Does mode: 'no-cors'
work when the browser has a native fetch implementation? (like newer chrome)
from isomorphic-fetch.
@npassaro thanks very much, that was exactly the issue for me. What's odd that every line of my previous code without it worked.
from isomorphic-fetch.
In my own case i changed the content type to 'x-www...' encoding then used the 'form-urlencoded' npm package to convert json to url-form
from isomorphic-fetch.
Just to tail this with the solution that solved the problem for me.
`var myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
fetch('/contact-form', {
method: 'POST',
headers: myHeaders,
mode: 'cors',
cache: 'default',
body: JSON.stringify(fields)
}).then(() => {
dispatch(contactFormSubmitSuccess());
});`
from isomorphic-fetch.
@dwilt the code that i have to send the data is
const data={
disPrice: 53,
subExp_id: '5b113df77860fb4e57aa8cef',
promocode: 'get6',
};
AddpromoCode: async function (data) {
return await fetch(API_BASE_URL + '/admin/insertPromocode', {
method: 'POST',
mode: 'no-cors',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify(data)
})
.then((response) => {
setTimeout(() => null, 0);
console.log('AppUtil then--' + JSON.stringify(response.json()));
return response.json();
})
.catch((err) => {
console.log('AppUtil err ' + err)
})
},
the response that i get is
{ '{"disPrice":53,"subExp_id":"5b113df77860fb4e57aa8cef","promocode":"get6"}': '' }
in this format.
could you help me with it
from isomorphic-fetch.
from isomorphic-fetch.
@npassaro thanks it worked.. but i had to remove the mode too.. apparently it was creating an issue
from isomorphic-fetch.
Guys if you tried changing the headers and still didn't work maybe the problem is in the server-side. If you're using body-parser, here's my solution:
- Declare a variable
const urlBodyParser = bodyParser.json()
- Then use it in routes
router.post('/some-url', urlBodyParser, (req, res) => { //... })
OR
- Use it as middleware
// For 'application/x-www-form-urlencoded' to work
router.use(bodyParser.urlencoded({ extended: false }));
// For 'application/json' to work
router.use(bodyParser.json());
I hope this helps.
from isomorphic-fetch.
I have a weird issue here. The api post method is triggered on click, for first time it returns empty object from the second click it queues i.e 1st fetched API's data is populated and 2nd fetched Api's data is populated on 3rd click so on. XHR files loading is working fine on console. I tried almost all the proposed inputs here nothing worked out for me.
from isomorphic-fetch.
hope this helps:
headers: {'Content-Type':'application/x-www-form-urlencoded'},
This solved my issue
I m salty this work and not application/json though at intended
from isomorphic-fetch.
hope this helps:
headers: {'Content-Type':'application/x-www-form-urlencoded'},
You are a life saver!
from isomorphic-fetch.
Related Issues (20)
- Upgrade node-fetch to >= 2.3.0 to fix semantic-release users that use styled-components HOT 2
- Fix version of whatwg-fetch HOT 1
- eiddccgeilvtdejdrvblujinlecirnvcbbnnnunegklr
- AbortController not working with this library HOT 4
- URLSearchParams in body doesn't set content-type to x-www-form-urlencoded
- Is this library still been maintained? HOT 4
- Tag a new version with the security fix HOT 11
- Add v3.0.0 release notes HOT 2
- How to handle error messages from server - Question HOT 1
- Node.js - realFetch.call is not a function HOT 8
- Isomorphic-fetch Typescript setup HOT 2
- Upgrade node-fetch to version 2.6.1 or 3.0.0-beta.9 HOT 1
- fetch api
- update node-fetch to v3.x HOT 7
- Security risk
- Found a possible security concern HOT 2
- Interceptors
- How to access the referer using isomorphic fetch library? An example would help!
- Dual Form
- Isomorphic fetch returns response with empty stream body HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from isomorphic-fetch.