2

I am working on a project where

  1. My APIs are written in Express.js (4.16)- in PORT: 1337
  2. Front end app is in React.js (16.2) - in PORT: 3000

So there are several APIs i need to call from React.js app, the problem am facing is:

PROBLEM IS -

DOESN'T WORK at all- fetch() API

fetch('localhost:1337/rest/api', {
    body: JSON.stringify( {name: "Sidd", "info": "Lorem ipsum dolor .."} ),
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    mode: 'no-cors',
    method: 'post'
})

When am using fetch() API, I am not getting the request body in my API defined in Express.js

console.log(req.body) // On logging the request body
{} // am getting this [empty]

WORKS- jQuery AJAX

$.ajax('localhost:1337/rest/api', {
    type: 'post',
    data: {name: "Sidd", "info": "Lorem ipsum dolor .."},  
    dataType: 'application/json',
    success: function (data, status, xhr) {
        console.log('status: ' + status + ', data: ' + data);
    },
    error: function (jqXhr, textStatus, errorMessage) {
        console.log('Error' + errorMessage);
    }
});

However am getting No 'Access-Control-Allow-Origin' header is present on the requested resource. ERROR!

But at least am GETTING the request body in my API in this case. Also tested my APIs through POSTMAN and they work totally fine. I have seen all the discussions out there online but nothing works.

Oh! I would also like to add this - In my Express.js setup am using body-parser properly

app.use(bodyParser.json({limit: '2mb'}));                           // 2mb file upload limit
app.use(bodyParser.urlencoded({limit: '2mb', extended: true}));     // 2mb file upload limit

WHAT I WANT!

  1. Solution for fetch() API
  2. If NOT fetch() API, how to remove the No 'Access-Control-Allow-Origin' error from my jQuery Ajax call.
  3. What am I doing wrong?

Thanks guys!

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46
  • Possible duplicate of [how-to-enable-cors-from-nodejs-server](https://stackoverflow.com/questions/39990550/how-to-enable-cors-from-nodejs-server/39990970#39990970) – Shubham Khatri Mar 21 '18 at 06:45

1 Answers1

2

Since 1337 and 3000 are the different ports, so you are encountering CORS request.

First, set mode: cors in fetch request, and then add a router handler

router.use((req, res, next) => {
  res.header('access-control-allow-origin', 'http://localhost:3000')
  res.header('Access-Control-Allow-Credentials', true)
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('Access-Control-Max-Age', 1728000)
  if (req.method === 'OPTIONS') {
    return res.json({ status: 0, message: '', payload: null })
  }
  next()
})

before your rest/api handler.

After doing that, you are good to go.

L_K
  • 2,838
  • 2
  • 16
  • 36
  • Well it will solve the cors prob +1 for that, but what bout the [fetch API]? Any clue? – Siddhartha Chowdhury Mar 21 '18 at 10:07
  • You can read the [Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) documentation for more details. And if you are confused about the `mode` property, please check out [Request()](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request) – L_K Mar 22 '18 at 01:50
  • Your answer helped me to realise I need to allow Credentials on my CORS related settings in a Django app. So thanks for this. – Kim Stacks May 06 '18 at 07:25