javascript - 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",
});
邮差
解决方案
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 标头。
推荐阅读
- ruby-on-rails - 在 Rspec 请求测试中使用 Session、Cookie 或 Current_something
- azure - 如何将 azure 文件共享挂载到 linux vm 上的现有目录
- viewbag - 将 ViewBag 值传递给 ParttailView MVC
- r - R:堆叠的 geom_area 图显示空白多边形
- c - 如何在 C 中的函数调用之间保留联合成员的值?
- java - 如何使用 SnakeYaml 加载自定义对象列表
- jenkins-pipeline - 执行成功后条件时出错:hudson.AbortException:未找到测试报告文件。配置错误?
- ios - 捕获两个图像并将其显示到两个 UIImageView
- r - 如何在R中按组按分钟填写缺失的日期
- c++ - 支持 ActiveX 控件中的模式和非模式对话框