用 express.json 做一个空的 post 请求

编程入门 行业动态 更新时间:2024-10-05 09:32:16

用 express.json <a href=https://www.elefans.com/category/jswz/34/1769682.html style=做一个空的 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 请求

本文发布于:2024-05-30 17:59:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:做一个   express   json   post

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!