【问题标题】:I keep getting undefined from node js express post request body我不断从 node js express post 请求正文中获取未定义
【发布时间】:2021-09-19 11:34:07
【问题描述】:

我尝试获取 post req.body 值,但是当我使用 console.log 时,我一直不确定(“express”:“^4.17.1”,) 我试过没有body-parser和body-parser,我一直得到相同的结果 我尝试了 StackOverflow 中可用的所有解决方案,但我得到的结果与您在 server.js 中看到的结果相同

//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const _ = require("lodash");
const mongoose = require("mongoose");
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:true}));
//app.use(bodyParser.urlencoded({ extended: true }))
//var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(express.static("public"));
app.use(cors());


app.get("/", (req, res) => 
{
    res.send("Hello");
});

app.post("/login", async (req, res) => {
    // const username = req.body.username;
    // const  password  = req.body.password;
    const {username , password } = req.body;
    console.log("username : " + username);
    console.log(req.body);
    res.json(username);
});



let port = process.env.PORT;
if (port == null || port == "") {
  port = 5000;
}

app.listen(port, function() {
  console.log("Server has started Successfully at port " + port);
});

这是邮递员的要求

localhost:5000/login?username="salem"&password=1234567

并在 package.json 下方

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Salem",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "lodash": "^4.17.21",
    "mongoose": "^5.13.2"
  }
}

我希望这能让我清楚地了解我的问题

最好的问候 塞勒姆

【问题讨论】:

  • 您没有在邮递员中发送请求正文 - URI 搜索值不是请求正文
  • curl --location --request POST 'localhost:5000/login' \ --header 'Content-Type: application/json' \ --data-raw '{ "username": "salem", "password": "1234567" }' 使用此有效负载,您将获得正文中的数据。目前,您将数据作为查询参数传递,只能通过 req.query 访问。要从 body 访问数据,您需要在 body 中传递它,如上面的有效负载所示。
  • 你放的所有东西? (问号)可以通过请求对象的参数访问,查询参数用于get方法而不是post方法。所以你最好从正文中传递用户名和密码。

标签: javascript node.js json express body-parser


【解决方案1】:

您将数据作为查询参数传递

localhost:5000/login?username="salem"&password=1234567

但从 req.body 中获取值

const {用户名,密码} = req.body;

你应该使用的是:

var username = req.query.username;
var password = req.query.password;

【讨论】:

  • 谢谢您的解释
【解决方案2】:

您必须将用户详细信息从邮递员发送到正文,或者您可以使用查询对象从 URL 中检索相同的内容。

req.query

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 2022-01-20
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多