我正在尝试从客户端页面向服务器发送字符串,但是服务器接收到一个空对象。这是我的客户端代码:
fetch("/sugestions/sugestions.txt", {
method: "POST",
body: JSON.stringify({ info: "Some data" }),
headers: {
"Content-Type": "application/json; charset=utf-8"
}
})
.then(res => {
if (res.ok) console.log("Yay it worked!");
else window.alert("Uh oh. Something went wrong!\n" + res);
});
这是我的服务器端代码:
const express = require("express");
const url = require("url");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
const port = process.env.PORT || 8080;
app.set("view engine", "ejs");
app.use(bodyParser());
app.post("/sugestions/*", (req, res) => {
info = JSON.parse(req.body);
fs.appendFile(path("req").pathname, info.info, (err) => {
if (err) res.status(404).end();
else res.status(200).end();
});
});
app.listen(port);
如果重要的话,以下是路径函数:
const path = req => url.parse(`${req.protocol}://${req.get("host")}${req.originalUrl}`, true);
茅侃侃
千巷猫影
相关分类