【问题标题】:ExpressJS shows request body as empty when it isn't emptyExpressJS 在请求正文不为空时将其显示为空
【发布时间】:2021-08-29 11:27:13
【问题描述】:

我有一个网站和一个快速服务器正在运行。 在网站中,用户可以输入他们的用户名和密码。 当他们点击登录按钮时,请求被发送到服务器,请求正文中的用户名和密码作为 JavaScript 对象。

这是网站代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Log In</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>

    <h1>Log In</h1>

    <div id="i">
      <input type="text" name="u" id="u" placeholder="Username">
      <input type="password" name="p" id="p" placeholder="Password">

     <input type="submit" onclick="login()" value="Log In">
     <div id="msg"></div>
    </div>

    <script src="script.js"></script>

  </body>
</html>

JS:

let u = document.getElementById("u");
let p = document.getElementById("p");
let msg = document.getElementById("msg");

let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log("Server request is ready. Press login to send request.")
    }
};

//login function triggered when user clicks login
function login() {
  data = {
  "username": u.value,
  "password": p.value
  }
  xhttp.open("POST", "SERVER_URL", true);
  xhttp.send(data)
}

但在服务器端,请求正文显示为空:

// environment variables
const client = process.env['MAIN_CLIENT'];

// imports
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');


//init
const app = express();



app.use(bodyParser.urlencoded({ extended: true }));//app.use(bodyParser);
app.use(bodyParser.json());


app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`)
})


app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", client);
  
  next();
});


app.post(`/data`, (req, res) => {
  console.log(req.body)

  u = req.body.u;
  p = req.body.p;
  data = process.env; 
  console.log("----------------") 
  

  if (data[u] == p) {
    console.log(`\n-/-/-/-/-/-/-/-/-/-/-/-/\nA user just logged in.\nUsername: ${u}\n-/-/-/-/-/-/-/-/-/-/-//-/ \n`)
    res.send(true)
  }
  else{
    console.log("no")
    res.send(false)
  }
});

app.listen(3000, () => {console.log('ready!')});

每当我尝试登录时,它都会将用户名显示为undefined。请求正文显示为{} 此外,变量 CLIENT 是网站 URL。 我是否以错误的方式发送请求?我访问请求正文是否错误?

【问题讨论】:

    标签: javascript node.js express request xmlhttprequest


    【解决方案1】:
    • 您应该将所有必要的代码包装在login() 函数中:获取输入值,初始化 XMLHttpRequest,发送请求
    • 您需要为请求提供Content-Type,它可以是application/jsonapplication/x-www-form-urlencoded,因为您在服务器端使用了2 个必要的中间件。在下面的代码中,我使用了application/x-www-form-urlencoded 中描述的document
    //login function triggered when user clicks login
    function login() {
    
      // get input value
      let u = document.getElementById("u").value;
      let p = document.getElementById("p").value;
      let msg = document.getElementById("msg").value;
    
      // init the request
      let xhttp = new XMLHttpRequest();
      xhttp.open("POST", "SERVER_URL", true);
    
      // Send the proper header information along with the request
      xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    
      xhttp.onreadystatechange = function() { // Call a function when the state changes.
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            // Request finished. Do processing here.
        }
      }
      xhttp.send(`username=${u}&password=${p}`);
      
    }
    

    【讨论】:

    • 当我记录正文时,它显示:{ username: '[object HTMLInputElement]', password: '[object HTMLInputElement]' }
    • 我编辑了我的答案。我忘了.value 从输入字段中获取值
    【解决方案2】:

    使用 JSON.stringify 发送数据。

    function login() {
      data = {
      "username": u.value,
      "password": p.value
      }
    
      xhttp.open("POST", "/token", true);
      xhttp.setRequestHeader('Content-type', 'application/json');
      xhttp.send(JSON.stringify(data))
    }
    

    再补充一点,express自带解析器,不需要添加外部解析器。

    app.use(express.urlencoded({extended:true}))
    app.use(express.json())
    

    【讨论】:

      【解决方案3】:

      使用 xhttp.setRequestHeader("Content-Type", "application/json"); 并再次尝试发出请求。您的请求标头可能不足以让后端了解您正在发送 json 数据。

      【讨论】:

      • 好吧,这就带来了一个新问题。我在调用open 之后和调用send 之前调用了setRequestHeader 函数。然后出现错误:Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
      【解决方案4】:

      login 函数中,您将usernamepassword 作为密钥发送并在服务器端访问错误的密钥:

      app.post(`/data`, (req, res) => {
        console.log(req.body)
        const { username, password } = req.body;
        const data = process.env; 
        console.log("----------------") 
       
        if (data[u] == p) {
          console.log(`\n-/-/-/-/-/-/-/-/-/-/-/-/\nA user just logged in.\nUsername: ${u}\n-/-/-/-/-/-/-/-/-/-/-//-/ \n`)
          res.send(true)
        }
        else{
          console.log("no")
          res.send(false)
        }
      });
      

      【讨论】:

      • 我试过这个:const { u, p } = req.body;,但没有成功。看起来整个 req.body 是空的。
      猜你喜欢
      • 2019-04-12
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      相关资源
      最近更新 更多