javascript - JavaScript - 无法获取 /api/list
问题描述
我正在一个用户应该能够将项目发布到列表的网站上工作。现在,当我尝试发布某些内容时,会出现错误提示
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity).
在控制台中单击它时,它会打开一个新的水龙头,它只是说
Cannot GET /api/list
同样在命令提示符下,它说
Unhandled rejection Error: Can't set headers after they are sent.
有谁知道为什么会这样以及我能做些什么来解决它?以下是我的一些代码片段:
索引.HTML:
fetch('/api/list', options)
.then(response => response.json())
.then(response => {
if (response.status == 'OK') {
console.log('song is added')
getList(items)
} else {
alert(response.message)
}
})
}
服务器.js:
app.post('/api/list', userIsAuthenticated, (req, res) => {
let {
titleArtist
} = req.body
let user_id = req.session.user.id
// seaching for user id in database
let query = {
where: {
userId: user_id
}
}
它也可能在代码中的其他地方出错。让我知道我是否应该发布更多代码片段。
解决方案
This is because you are making a GET request to POST API.
This is how you can make POST request
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
推荐阅读
- facebook - AR Studio 脚本问题
- dart - Flutter:将盒子阴影添加到透明容器
- python - Django 不应用 css 文件或显示图像
- c# - if 语句或 for 循环
- javascript - 当其他对象也被传入时,为什么 Object.assign({}, ...) 带有一个空的对象字面量?
- javascript - 第一次尝试启动解析服务器项目时找不到模块“http2”
- openssl - 用于 ECDSA 证书的 openssl“无共享密码”(RSA 工作正常)
- javascript - 如何显示数组数据?
- netlogo - 如何在 Netlogo 中打开同一个文件两次?(两个文件指针)
- git - 为什么我的“git log”输出中的提交的“作者”条目与我在提交时登录到 Heroku 的用户不同?