尝试在已初始化的页面上附加消息(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/