首页 > 解决方案 > Axios 发布发送正文,但正文未使用 fetch 和 Postman 定义

问题描述

我无法使用 fetch 或 Postman 发送帖子正文,但我可以使用 Axios 发送正文。

Axios 返回:User name = Fred, password is Flintstone

但是 Postman 和 fetch 都返回User name = undefined, password is undefined

如何使用 fetch 和 postman 获取帖子正文?

服务器文件

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const axios = require("axios");

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

app.post("/login", (req, res) => {
  var user_name = req.body.user;
  var password = req.body.password;
  console.log("User name = " + user_name + ", password is " + password);
  res.end("yes");
});

app.listen(3000, () => {
  console.log("Started on PORT 3000");
});

爱讯

axios.post("http://localhost:3000/login", {
  user: "Fred",
  password: "Flintstone",
});

获取(客户端)

fetch("http://localhost:3000/login", {
  method: "POST",
  body: JSON.stringify({ user: "Fred", password: "Flintstone" }),
  mode: "no-cors",
});

邮差

在此处输入图像描述

标签: javascriptnode.jsaxiosfetchpostman

解决方案


fetch不默认发布 JSON,这就是您必须显式编码正文的原因。您还需要告诉服务器您正在发送 JSON。

未经 CORS 许可,您不能这样做,因此您不能将模式设置为no-cors.

const headers = new Headers();
headers.append("Content-Type", "application/json");

fetch("http://localhost:3000/login", {
  method: "POST",
  body: JSON.stringify({ user: "Fred", password: "Flintstone" }),
  headers
});

Postman 的问题可能是相同的(但在 UI 屏幕截图中不可见):您需要设置 Content-Type 标头。


推荐阅读