【问题标题】:Express REST API fails when parsing a payload?解析有效负载时 Express REST API 失败?
【发布时间】:2019-11-20 18:54:28
【问题描述】:

我是 NodeJS + Express 开发的新手。我想构建一个可以通过 POST 接收 JSON 数据的 REST API。我能够在 Express 中构建 API,并从邮递员软件的传输中接收 json 有效负载。但是,当我尝试从网络浏览器使用 javascript 的 fetch() 函数模拟相同的行为时,我的 express rest api 崩溃并出现以下错误:

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at parse (/home/johncomputer/projects/tt/node_modules/body-parser/lib/types/json.js:89:19)
    at /home/johncomputer/projects/tt/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:224:16)
    at done (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/home/johncomputer/projects/tt/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:215:7)
    at endReadableNT (_stream_readable.js:1184:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

我的 express 项目中只有一个名为 src/app.js 的文件:

const express = require('express')
const port = process.env.PORT
var cors = require('cors')

const app = express()

app.use(cors())
app.use(express.json())

router = express.Router()

router.post('/users', async (req, res) => {
    try {
            console.log("+++++++++++")
            console.log(req)
            console.log("=========")
        res.status(201).send({ "world":true })
    } catch (error) {
        res.status(400).send(error)
    }
})

app.use(router)

app.listen(port, () => {
    console.log(`Server running on port ${port}`)
})

我不确定我是否正确使用了cors(),但我把它扔在那里是为了解决导致我的fetch() 生成失败的网络连接错误的飞行前选项问题(它没有'不会发生在邮递员身上)。

这是我的 javascript 获取代码:

const postData = {"name":"John","email":"john@john.com","password":"chocolate-raisins!!!"};


fetch("http://johnserver.com:3000/users", {
  method: "POST",
  headers: {'Content-Type': 'application/json'},
  body: postData
}).then((response)=>{
  console.log(response);
  if(!response.ok) return {}
  return response.json();
}).then((result)=>{
  console.log(result);return;
}).catch(function(error){
    alert("Post Request Error: "+error.toString());
});

我做错了什么导致我的 API 使用 fetch() 而不是 postman 失败?


编辑

我获取的response 变量的输出是这样的:

Response { type: "cors", url: "http://johnserver.com:3000/users", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }

我获取的result 变量的输出是这样的:

{ }

【问题讨论】:

  • 你能在你的获取结果中打印response吗?还有当你调用获取块代码的时候??
  • 我用您要求的详细信息更新了我的答案

标签: node.js rest express


【解决方案1】:

请在您的 fetch 方法上执行此操作。

body:post Data 做--> JSON.stringify(postData)

还有你的 then 函数首先 return response.json() 然后 检查你想要的任何参数。

【讨论】:

    【解决方案2】:

    你没有发送有效的你需要对你的对象进行字符串化。

    fetch("http://localhost:3000/users", {
                method: "POST",
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ "name": "John", "email": "john@john.com", "password": "chocolate-raisins!!!" })
            }).then((response) => {
                if (!response.ok) {
                    return {};
                }
                return response.json();
            }).then((response) => {
                console.log(response); return;
            }).catch(function (error) {
                alert("Post Request Error: " + error.toString());
            });
    

    【讨论】:

      猜你喜欢
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-27
      • 2016-12-27
      • 1970-01-01
      • 2019-04-23
      • 2018-01-26
      相关资源
      最近更新 更多