简体   繁体   中英

request body is not passing from Next.js to Node.js server

I was wondering if you can help me on this one.

Calling function:

function apiCreate(url, product) {
console.log('Posting request API...' + JSON.stringify(product) );
fetch(url, {
    dataType: 'json',
    method: 'post',
    body: product
}).then(function(response) {
    console.log("we did it")
  return response.json();
}).then(function(data) {
    console.log('Created Gist:', data.html_url);
});

And receiving is:

router.post('/create', (req, res) => {
    console.log('catalog product create Called.');

    console.log('addProduct Called..');
    console.log('req: '+ JSON.stringify(req.body));

I can hit the end point but the body is not in the "req" object.

Thank you.

Missing the Header, try this..

function apiCreate(url, product) {
      try {
        fetch(url, {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(product)
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.log(error))  
      } catch (err) {
        console.log(err)
      }
}

Receiving...

router.post('/create', (req, res) => {
    console.log('catalog product create Called.');

    console.log('addProduct Called..');
    console.log(`req ${body.req}`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM