I am trying to make an AJAX post to my Express API.
I am expecting {user:Todd} to be returned in my data object, however whenever i try to log the request body, the object shows as empty./
$.ajax({
url: '/api/test',
type: 'POST',
data: ({user: "Todd"})
})
I always test my endpoints with cURL as well, and i remember that i needed to pass the header "Content-Type: application/json" for this to work in the past.
$.ajax({
url: '/api/test',
type: 'POST',
data: ({user: "Todd"}),
contentType: 'application/json'
})
I am listening for requests on my NodeJS server and the above request doesnt even touch my server, while the first one sends empty JSON.
I am officially confused! How can adding a header break my API like this?
Here is the simple source code to my API.
var express = require('express');
var bodyParser = require('body-parser')
let app = express();
let port = 3000
app.use(bodyParser.json({
limit:'150mb'
}));
app.post('/api/test', function(req, res) {
console.log(req)
console.log(req.body)
});
app.listen(port, () => console.log(`App listening on port ${port}`));
Try this inside your html script tag
const apiHost = "http://localhost:3000";
$.ajax({
url: `${apiHost}/api/test`, //add full path of your host
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ //JSON data needs to be stringified before its sent through http.
'user': 'hello'
})
})
The reason your server is not receiving the req is because of blocked/restricted CORS .
Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos. -Wikipedia
So do a npm install --save cors
and use the code below
var express = require('express');
var bodyParser = require('body-parser')
var cors = require('cors');
let app = express();
let port = 3000
app.use(cors()); // add cors to middleware
app.use(bodyParser.json());
// for parsing application/json which was stringified in the ajax front-end
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/test', function (req, res) {
res.send("<h1>WOrking</h1>")
})
app.post('/api/test', function (req, res) {
console.log(req.body)
});
app.listen(port, () => console.log(`App listening on port ${port}`));
I managed to solve this yesterday. I appreciate all the help.
It turns out that i needed to add the following code to my express body parser:
app.use(bodyParser.urlencoded({ extended: true }));