gpt4 book ai didi

javascript - 如何为 Node.js 中的 post 模块修复 "ReferenceError: xxx is not defined"

转载 作者:行者123 更新时间:2023-11-30 13:58:51 25 4
gpt4 key购买 nike

尝试在已初始化的页面上附加消息(JSON 格式)时出现错误。

这是我在 server.js 文件上写的一段代码,我运行“nodemon”来启动服务器。

var messages = [{R1: 0}, {R2: 0}]
app.get('/votes', (req, res) =>{
res.send( messages )
})

app.post('/votes', (req, res) =>{
votes.push(req.body)
res.sendStatus(200)
})

运行“nodemon .\server.js”后,我导航到 http://localhost:8080/votes我在那里看到了数据。

我想在从 html 页面获取输入后向该页面附加更多数据。单击按钮后执行此代码时出现错误。

这是我的代码:

<body>
// some logic here
<script>
$(() => {
$("#submit").click(()=>{
var message = [ { R1: $("#input").val()},
{ R2: $("#input2").val()}]
postMessage(message)
})
})
function postMessage(message) {
$.post('http://localhost:8080/votes', message)
}
</script>
</body>

它不起作用,我的服务器控制台出现错误:ReferenceError: votes 未定义

最佳答案

错误在这里:

app.post('/votes', (req, res) =>{
votes.push(req.body)
res.sendStatus(200)
})

req.body 应该是 votes 并且你应该将它推送到 res:

app.post('/votes', (req, res) =>{
res.push(votes)
res.sendStatus(200)
})

votes 应该首先定义

关于javascript - 如何为 Node.js 中的 post 模块修复 "ReferenceError: xxx is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com