如何在 JavaScript 中使用 'body-parser'?

How can I use 'body-parser' in JavaScript?

我正在通过 Node.js 学习 Web 服务器。 当我尝试使用 Body-parser 时,我无法再进步了。 状态代码是成功的。 好像成功了。我收到回复信息。但是在浏览器上不显示。

问题是什么? 我的代码如下。

//basic-server.js

const express = require('express')
const cors = require('cors');
const app = express()

const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()

const PORT = 5000;
const ip = 'localhost';

app.use(cors())

app.get('/', (req, res) =>{
  res.send("hello")
})

app.post('/lower', jsonParser, (req, res) =>{
  
 res.send(req.body.body.toLowerCase())
  
})
app.post('/upper', jsonParser, (req, res) =>{
  
  res.send(req.body.body.toUpperCase())
})



app.listen(PORT, ip, () => {
  console.log(`http server listen on ${ip}:${PORT}`);
});
// App.js

class App {
  init() {
    document
      .querySelector('#to-upper-case')
      .addEventListener('click', this.toUpperCase.bind(this));
    document
      .querySelector('#to-lower-case')
      .addEventListener('click', this.toLowerCase.bind(this));
  }
  post(path, body) {
    
    fetch(`http://localhost:5000/${path}`, {
      method: 'POST',
      body: JSON.stringify({body}),
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(res => {
        return res.json()})
      .then(res => {  
        this.render(res);
      });
  }
  toLowerCase() {
    const text = document.querySelector('.input-text').value;
    this.post('lower', text);
  }
  toUpperCase() {
    const text = document.querySelector('.input-text').value;
    this.post('upper', text);
  }
  render(response) {
    const resultWrapper = document.querySelector('#response-wrapper');
    document.querySelector('.input-text').value = '';
    resultWrapper.innerHTML = response;
  }
}

const app = new App();
app.init();

开发者工具控制台报错

'Uncaught (in promise) SyntaxError: Unexpected token A in JSON at position 0
Promise.then (async)
post @ App.js:21
toUpperCase @ App.js:31'.

以下信息来自网络标签。

-preflight
Request URL: http://localhost:5000/upper
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Fri, 28 May 2021 10:15:31 GMT
Keep-Alive: timeout=5
Vary: Access-Control-Request-Headers
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:5000
Origin: null
Pragma: no-cache
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
-fetch
Request URL: http://localhost:5000/upper
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 1
Content-Type: text/html; charset=utf-8
Date: Fri, 28 May 2021 10:15:31 GMT
ETag: W/"1-bc1M4j2I4u6VaLpUbAB8Y9kTHBs"
Keep-Alive: timeout=5
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 12
Content-Type: application/json
Host: localhost:5000
Origin: null
Pragma: no-cache
sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
{body: "a"}
body: "a"
-Response
A

您正在正确使用 bodyparser。问题出在你的代码中,你只返回一个符号 A,客户端试图解析这个不正确的 JSON,这就是它失败的原因。

您可以将 res.send(req.body.body.toUpperCase()) 更改为 res.send(JSON.stringify(req.body.body.toUpperCase())) 来解决问题。

您得到的响应不是 json 格式,因此请尝试将其添加到 server.js 中请求上方的代码中;

app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());
如果它有效,那么问题是您发送的不是 json 的其他格式,因此 jason 解析器将无法工作。