I making a web app with node.js.I have a API on /api/users/register that takes name and password.I want to sent a POST request to that adress with XMLHttpRequest.The request comes to the API but i cant figure out how to access name and password. I tried to access with req.body but it returns an empty list.Is there any other method for accessing data?
Heres my XML request file
const submitBtn = document.getElementById('submitBtn')
function registerUser() {
const name = document.getElementById('name')
const password = document.getElementById('password')
const xhr = new XMLHttpRequest()
xhr.open('POST', '/api/users/register')
xhr.send(JSON.stringify({name:name.value, password:password.value}))
}
submitBtn.addEventListener('click', registerUser)
CodePudding user response:
Since you are passing a string to send()
, XHR is going to set a Content-Type: text/plain
request header by default. The first thing you need to do is override that.
xhr.setRequestHeader("Content-Type", "application/json");
The in the server-side code you haven't shared with us, you need to read the request body, parse it as JSON, and (assuming you want to read it from req.body
) assign it to req.body
.
Assuming you are using Express.js, see the documentation which says:
req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
So:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
});
app.use(express.json());
app.post('/some-path', (req, res) => {
const { name, password } = req.body;
console.log(name, password);
res.send("some response");
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})