[英]SyntaxError: Unexpected token = in JSON at position 11 at JSON.parse (<anonymous>)
I can't figure it out why this is happening when I send a request via Insomnia using the PUT method.当我使用 PUT 方法通过 Insomnia 发送请求时,我无法弄清楚为什么会发生这种情况。 I'am trying to put a new title in a object that is in the projects[] array but it's not working out.我正在尝试在 projects[] 数组中的 object 中添加一个新标题,但它没有成功。 This is the JS code:这是JS代码:
const express = require('express');
const server = express();
server.use(express.json());
const projects = [];
server.post('/projects', (req, res) => {
const { id, title } = req.body;
const project = {
id,
title,
tasks: []
};
projects.push(project);
return res.json(project);
})
server.get('/projects', (req, res) => {
return res.json(projects);
})
server.put('/projects/:id', (req, res) => {
const { id } = req.params;
const { title } = req.body;
for (let i = 0; i < projects.length; i++) {
if(projects[i].id == id){
projects[i].title = title;
}
}
return res.json(project);
})
server.delete('/projects/:id', (req, res) => {
const { id } = req.params;
const projectIndex = projects.findIndex(p => p.id == id);
projects.splice(projectIndex, 1);
return res.json(projects);
})
server.listen(3000);
This is the request I sent:这是我发送的请求:
{
"title" = "new title"
}
This are my dev dependencies:这是我的开发依赖项:
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.4"
}
}
The request you are sending is not valid.您发送的请求无效。 You have used = in json.您在 json 中使用了 =。 It should be colan (:): Please replace this to:它应该是 colan (:): 请将其替换为:
{
"title" : "new title"
}
Hope it will work!希望它会奏效!
Your Projects array is empty that means the code inside the loop will never be executed.您的 Projects 数组是空的,这意味着循环内的代码将永远不会被执行。
const projects = [{ id: 2, title: "old title" }];
app.put("/projects/:id", (req, res) => {
const { id } = req.params;
const { title } = req.body;
for (let i = 0; i < projects.length; i++) {
if (projects[i].id == id) {
projects[i].title = title;
}
}
res.send(projects);
});
After changing the code you posted to this and sending a put request to /projects/2
with the body {"title": "new title"}
在更改您发布到此的代码并向/projects/2
发送一个 put 请求后,正文为{"title": "new title"}
The response is回应是
[
{
"id": 2,
"title": "new title"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.