首页 > 解决方案 > 从客户端接收 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()
	})
})

谢谢你的帮助 !

标签: javascriptnode.jsjsonexpress

解决方案


您没有在 中处理来自服务器的响应XHR.send(dataToSend),但您应该能够在 Chrome Devtools 的网络选项卡中看到响应(或其他浏览器中的等效项)。


推荐阅读