简体   繁体   English

ExpressJS 在请求正文不为空时将其显示为空

[英]ExpressJS shows request body as empty when it isn't empty

I have a website and an express server running.我有一个网站和一个快速服务器正在运行。 In the website, the user can input their username and password.在网站中,用户可以输入他们的用户名和密码。 When they click the login button, the request is sent to the server with the username and password in the request body as a JavaScript object.当他们单击登录按钮时,请求将发送到服务器,请求正文中的用户名和密码为 JavaScript object。

Here's the website code:这是网站代码:

<!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: 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)
}

But on the server-side, the request body shows empty:但在服务器端,请求正文显示为空:

// 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!')});

Whenever I try to log in, it shows the username as undefined .每当我尝试登录时,它都会将用户名显示为undefined The request body shows as {} Also, the variable CLIENT is the website URL.请求正文显示为{}此外,变量CLIENT是网站 URL。 Am I sending the request in the wrong way?我是否以错误的方式发送请求? Am I accessing the request body wrong?我访问请求正文是否错误?

Use xhttp.setRequestHeader("Content-Type", "application/json");使用xhttp.setRequestHeader("Content-Type", "application/json"); and try making request once again.并尝试再次提出请求。 Your request headers may not be enough for the backend to understand that you are sending json data.您的请求标头可能不足以让后端了解您正在发送 json 数据。

In the login function, you are sending username and password as a key and accessing wrong keys on the server-side:login function 中,您将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)
  }
});
  • You should wrap all the necessary code in the login() function: get the input value, init the XMLHttpRequest, send the request您应该将所有必要的代码包装在login() function 中:获取输入值,初始化 XMLHttpRequest,发送请求
  • You need to provide the Content-Type for the request, it could be application/json or application/x-www-form-urlencoded because you've used 2 necessary middlewares on the server-side.您需要为请求提供Content-Type ,它可以是application/jsonapplication/x-www-form-urlencoded ,因为您在服务器端使用了 2 个必要的中间件。 In the below code, I use the application/x-www-form-urlencoded which is described in the document在下面的代码中,我使用了文档中描述的application/x-www-form-urlencoded
//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}`);
  
}

Use JSON.stringify to send data.使用 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))
}

Just one more note, express contains its own parsers, no need to add external parsers.再注意一点,express 包含自己的解析器,无需添加外部解析器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM