javascript - 从客户端接收 JSON 后 Res 无法正常工作
问题描述
我正在尝试制作一个简单的代码,但我有一个我无法理解的小问题。
所以,我正在尝试使用 POST 方法将 JSON 格式的表单发送到服务器(Express 4.16)。我的服务器接收到它(我可以通过控制台日志 req.body 看到它),但没有一个 res 方法起作用(它只是通过它,res.send,res.json,res.redirect ......并且没有任何错误。 .)。
有我的代码:
应用程序.js
const express = require('express')
const path = require('path')
const app = express()
app.use(express.urlencoded({extended: false}))
app.use(express.json())
app.use('/public', express.static(path.join(__dirname, 'static')))
app.get('/', (req,res) => {
res.sendFile(path.join(__dirname, 'static', 'index.html'))
})
app.post('/', (req,res) => {
console.log(req.body)
res.send(`You did it ${req.body.name} !! `)
})
app.listen('8080')
main.js
window.addEventListener("load", function () {
let form = document.getElementById("id-form")
function sendData() {
let XHR = new XMLHttpRequest()
let data = {}
for (const input of form.getElementsByTagName('input')) {
data[input.name] = input.value
}
XHR.open('POST', '/')
XHR.setRequestHeader('Content-Type', 'application/json')
let dataToSend = JSON.stringify(data)
XHR.send(dataToSend)
}
form.addEventListener("submit", function (event) {
event.preventDefault()
sendData()
})
})
谢谢你的帮助 !
解决方案
您没有在 中处理来自服务器的响应XHR.send(dataToSend)
,但您应该能够在 Chrome Devtools 的网络选项卡中看到响应(或其他浏览器中的等效项)。
推荐阅读
- javascript - 以自定义方式对数组进行排序?
- javascript - Reactstrap 工具提示被放置在整个 div 的底部,而不是它的子元素
- mysql - 如何通过 Node Js 模块文件运行 MySQL 查询
- c# - 为什么不能区域测试点的范围?
- javascript - 如何在 React with Typescript 中传递具有所需道具的组件数组?
- python - 如何使用 for 循环打印乘法表?
- node.js - 节点 RabbitMQ 消费消息并为每条消息做一些事情
- mysql - mysql group_concat 和 group by 不工作
- javascript - 数学函数总是显示 0 或根本不工作
- c++ - 有没有办法使用 libxml2 自动检测根标签中写入的命名空间?