做一个空的 post 请求"/>
用 express.json 做一个空的 post 请求
如果我尝试发出一个空请求,我不会以 json 格式发送数据,在标头应用程序中键入 json / json 以 html 的形式给出它,我必须知道如何解决它,因为它显示了路线和更多东西
我正在使用 app.use(express.json())
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at createStrictSyntaxError (D:\Programacion\VUEJS_NODEJS\backend\node_modules\body-parser\lib\types\json.js:160:10)
at parse (D:\Programacion\VUEJS_NODEJS\backend\node_modules\body-parser\lib\types\json.js:83:15)
at D:\Programacion\VUEJS_NODEJS\backend\node_modules\body-parser\lib\read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
at invokeCallback (D:\Programacion\VUEJS_NODEJS\backend\node_modules\raw-body\index.js:231:16)
at done (D:\Programacion\VUEJS_NODEJS\backend\node_modules\raw-body\index.js:220:7)
at IncomingMessage.onEnd (D:\Programacion\VUEJS_NODEJS\backend\node_modules\raw-body\index.js:280:7)
at IncomingMessage.emit (node:events:513:28)
at endReadableNT (node:internal/streams/readable:1359:12)
如果我使用 if(Object.keys(req.body).length === 0)
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at file:///D:/Programacion/VUEJS_NODEJS/backend/index.js:71:15
at Layer.handle [as handle_request] (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\index.js:328:13)
at D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\index.js:286:9
at Function.process_params (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\index.js:346:12)
at next (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\index.js:280:10)
at serveStatic (D:\Programacion\VUEJS_NODEJS\backend\node_modules\serve-static\index.js:75:16)
at Layer.handle [as handle_request] (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\Programacion\VUEJS_NODEJS\backend\node_modules\express\lib\router\index.js:328:13)
用express解决代码错误
回答如下:如果您发送
application/json
作为 content-type
,那么正文必须是合法的 JSON。故事结局。 SyntaxError: Unexpected end of JSON input
表示它不是合法的 JSON。
如果您不发送 JSON,则不要将
content-type
设置为 application/json
然后 express.json()
将不会尝试处理它。
或者,如果您真的希望它是
application/json
但没有任何数据要发送,则发送一个空对象作为 JSON。
更多推荐
用 express.json 做一个空的 post 请求
发布评论