I am working on a project where
- My APIs are written in Express.js (4.16)- in PORT: 1337
- 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!
- Solution for fetch() API
- If NOT fetch() API, how to remove the
No 'Access-Control-Allow-Origin'
error from my jQuery Ajax call. - What am I doing wrong?
Thanks guys!