GithubHelp home page GithubHelp logo

Comments (49)

dwilt avatar dwilt commented on May 31, 2024 73

@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.

npassaro avatar npassaro commented on May 31, 2024 55

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.

matthew-andrews avatar matthew-andrews commented on May 31, 2024 23

@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.

matthew-andrews avatar matthew-andrews commented on May 31, 2024 19

are you using the right body parser? @wallacyyy

https://github.com/expressjs/body-parser

from isomorphic-fetch.

matthew-andrews avatar matthew-andrews commented on May 31, 2024 18

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.

npassaro avatar npassaro commented on May 31, 2024 11

Hi, no-cors mode makes content-type header immutable. Make sure you have mode: 'cors' or the default. Hope it helps.

from isomorphic-fetch.

Roconda avatar Roconda commented on May 31, 2024 7

@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.

hbrannan avatar hbrannan commented on May 31, 2024 7

Just used the 'Content-Type' sol and it solved my problem!

from isomorphic-fetch.

wallacyyy avatar wallacyyy commented on May 31, 2024 4

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.

kevnk avatar kevnk commented on May 31, 2024 4

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.

dwilt avatar dwilt commented on May 31, 2024 4

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.

neoeahit avatar neoeahit commented on May 31, 2024 3

hope this helps:

headers: {'Content-Type':'application/x-www-form-urlencoded'},

from isomorphic-fetch.

npassaro avatar npassaro commented on May 31, 2024 2

@dwilt you have to send the body as JSON string. Do:

body: JSON.stringify({ name: 'Dan'})

from isomorphic-fetch.

npassaro avatar npassaro commented on May 31, 2024 2

@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.

npassaro avatar npassaro commented on May 31, 2024 1

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

Moreover, can you see you request in inspect > Network? Does your request appear exiting the browser with the expected body?

from isomorphic-fetch.

dwilt avatar dwilt commented on May 31, 2024 1

@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.

RohanDamani avatar RohanDamani commented on May 31, 2024 1

I had the same issue because of 'preflighting' -

http://stackoverflow.com/questions/1256593/why-am-i-getting-an-options-request-instead-of-a-get-request

The OPTION request shows as 'XHR' and the POST shows as 'Other'

from isomorphic-fetch.

vOtto avatar vOtto commented on May 31, 2024 1

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.

npassaro avatar npassaro commented on May 31, 2024 1

@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.

wallacyyy avatar wallacyyy commented on May 31, 2024

I'm having the same issue, how did you solve it ? @Roconda

from isomorphic-fetch.

tracker1 avatar tracker1 commented on May 31, 2024

@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.

XeeD avatar XeeD commented on May 31, 2024

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.

kevnk avatar kevnk commented on May 31, 2024

I'm also having this issue today.

from isomorphic-fetch.

ufukomer avatar ufukomer commented on May 31, 2024

Yea, it does not send post request to the server. Same problem...

from isomorphic-fetch.

kevnk avatar kevnk commented on May 31, 2024

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.

dwilt avatar dwilt commented on May 31, 2024

@npassaro tried that - still doesn't work.

from isomorphic-fetch.

dwilt avatar dwilt commented on May 31, 2024

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.

npassaro avatar npassaro commented on May 31, 2024

@dwilt What's the content-type header value sent in the post?

from isomorphic-fetch.

dwilt avatar dwilt commented on May 31, 2024

@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.

rbriski avatar rbriski commented on May 31, 2024

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.

npassaro avatar npassaro commented on May 31, 2024

@dwilt awesome! Glad I could help!

from isomorphic-fetch.

dwilt avatar dwilt commented on May 31, 2024

@npassaro you're awesome - thank you for your help.

from isomorphic-fetch.

Jaikant avatar Jaikant commented on May 31, 2024

@dwilt was the above issue on the server side or client side?

from isomorphic-fetch.

tamer-badawy avatar tamer-badawy commented on May 31, 2024

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.

pkrall520 avatar pkrall520 commented on May 31, 2024

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.

ZengTianShengZ avatar ZengTianShengZ commented on May 31, 2024

thank you for your help.

from isomorphic-fetch.

whitezo avatar whitezo commented on May 31, 2024

body = JSON.stringify(body) worked for me as well!

from isomorphic-fetch.

zulucoda avatar zulucoda commented on May 31, 2024

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.

tracker1 avatar tracker1 commented on May 31, 2024

@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.

theholiday avatar theholiday commented on May 31, 2024

@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.

usmansbk avatar usmansbk commented on May 31, 2024

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.

levous avatar levous commented on May 31, 2024

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.

radha-bacancy avatar radha-bacancy commented on May 31, 2024

@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.

pkrall520 avatar pkrall520 commented on May 31, 2024

from isomorphic-fetch.

radha-bacancy avatar radha-bacancy commented on May 31, 2024

@npassaro thanks it worked.. but i had to remove the mode too.. apparently it was creating an issue

from isomorphic-fetch.

darwinphi avatar darwinphi commented on May 31, 2024

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:

  1. Declare a variable
    const urlBodyParser = bodyParser.json()
  2. Then use it in routes
    router.post('/some-url', urlBodyParser, (req, res) => { //... })

OR

  1. 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.

Manoj-Ambati avatar Manoj-Ambati commented on May 31, 2024

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.

StarNab avatar StarNab commented on May 31, 2024

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.

abcjeff avatar abcjeff commented on May 31, 2024

hope this helps:

headers: {'Content-Type':'application/x-www-form-urlencoded'},

You are a life saver!

from isomorphic-fetch.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.