邮递员 HTTP 请求有效,但其各自的代码无效

时间:2021-07-14 00:36:08

标签: node.js bash http curl postman

首先,我使用 Postman 向我的 API 发出 POST 请求,并使用 JSON 正文:{ example: 'data' }。 接下来,我复制它生成的代码并用反引号替换所有反斜杠以使其适用于 Powershell,因此它看起来像这样:

curl --location --request POST 'localhost:3000/api/videogames' `
--header 'Content-Type: application/json' `
--data-raw '{"example":"data"}'

该请求在 Postman 中运行良好,但在 Node.js 中出现错误:

SyntaxError: Unexpected token e in JSON at position 1
    at JSON.parse (<anonymous>)
    at parse (C:\Users\sethm\code\nodewebapp1\node_modules\body-parser\lib\types\json.js:89:19)
    at C:\Users\sethm\code\nodewebapp1\node_modules\body-parser\lib\read.js:121:18
    at invokeCallback (C:\Users\sethm\code\nodewebapp1\node_modules\raw-body\index.js:224:16)
    at done (C:\Users\sethm\code\nodewebapp1\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (C:\Users\sethm\code\nodewebapp1\node_modules\raw-body\index.js:273:7)
    at IncomingMessage.emit (events.js:387:35)
    at endReadableNT (internal/streams/readable.js:1317:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)

它说 SyntaxError,所以我尝试使用单引号切换双引号,然后我尝试使用转义反引号将它们向上移动(因为反引号在 Powershell 中很特殊)。

没用。

然后我记录了标题。

然后我注意到 Postman 有一个标题“Accept-Encoding”,其值为“gzip、deflate、br”。所以我在 cURL 请求中使用了这些标头。我通过在代码中记录标头来确保我的 cURL 语法正确,但我仍然遇到相同的错误。

编辑:

这是我的 Node.js 代码:

import express from "express"
const app = express()
const port = 3000

app.use(express.json())

let videogames = {
  "count": 3,
  "list": [{
    "id": 1,
    "title": "ARK Survival",
    "released": 2017,
    "sales": 6800000
  },
  {
    "id": 2,
    "title": "Rainbow Six Siege",
    "released": 2014,
    "sales": 65000000
  },
  {
    "id": 3,
    "title": "Black Ops III",
    "relased": 2015,
    "sales": 59000000
  }]}

app.post("/api/videogames", (req, res) => {
  videogames.count += 1

  let newGame = req.body
  newGame.id = videogames.count
  
  videogames.list.push(newGame)

  res.end(JSON.stringify(videogames.list))
})

app.get("/api/videogames", (req, res) => {
  res.end(JSON.stringify(videogames.list, null, 4))
})

app.get("/api/videogame/:id", (req, res) => {
  let { id } = req.params
  res.end(JSON.stringify(videogames.list[id-1], null, 4))
})

app.listen(port, () => {
  console.log(`Listening at http://localhost:${port}`)
})

我想知道为什么 cURL 请求正文未定义而 Postman 请求正文有效。

0 个答案:

没有答案