I've been working on troubleshooting a very simple application and cannot assess why the request body of POST is undefined. I have used express.json() and body-parser and changed the Content-Type of the request to different formats and have gotten nothing back.
This is the backend code relevant to the issue
const morgan = require("morgan");
const { response } = require("express");
const { format } = require("morgan");
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.static("build"));
app.use(cors());
app.use(express.json());
app.use(morgan("combined"));
app.post("/api/phonebook/", (req, res) => {
const body = req.body;
console.log(req.body);
console.log(body.content);
if (!body.name) {
return res.status(404).json({
error: "no name",
});
}
const personObj = {
name: body.name,
phone: body.phone,
id: generateId(),
};
phonebook = phonebook.concat(personObj);
response.json(personObj);
});
And this is an example POST
POST http://localhost:3000/api/phonebook/
Content-Type: application/json
{
"name": "Bob",
"phone": 123-456
}
The server is up and running and doing GET and DELETE requests both work.
POST http://localhost:3000/api/phonebook/
Content-Type: application/json
{
"name": "Bob",
"phone": 123-456
}
On request parameter body, 123-456
Isn't number so it should have " " to be "123-456". Because 123-456 type is null so the parameter is undefined. Parsing stiringified number into integer is needed on the server.
Response parameters in callback func should be used properly. response.json
on end of callback function should be edited to res.json
as the callback function defined (res, 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.