? 使用 Fetch API 发出 POST 请求
正如您所提到的,您的服务器中需要一个 POST 路由来处理它。
您的前端应该使用新创建的对象对该端点进行 AJAX POST 调用。您可以使用Featch API 来做到这一点:
fetch('http://localhost:8080/api/friends', {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
name: "Ahmed",
photo: "https://media.licdn.com/.../foo.jpg",
scores: [5, 1, 4, 4, 5, 1, 2, 5, 4, 1],
}),
});
? 修改后端数据
那么,假设这只是一个简单的学习示例,在您的后端,您有两个选择:
- 将
friends.json 文件作为数组加载到内存中,然后将新元素推入其中。
- 在每个请求上加载、解析和保存
friends.json。
如果这是一个生产服务器,那么您可以考虑使用 REDIS、MongoDB 或任何其他满足您需求的数据库。
在这里你可以看到他们两个:
// This will be loaded and parsed already (only used in option 1):
const friends = require("../data/friends.json");
// Only used in option 2:
const fs = require('fs');
// Tell the server to parse JSON bodies in your requests:
const bodyParser = require("body-parser");
app.use(bodyParser.json()); // Support JSON-encoded bodies.
// Get existing friends:
app.post('/api/friends', function(req, res, next) {
// Option 1, persisted in memory:
res.json(friends);
// Option 2, loaded and saved everytime:
try {
res.json(JSON.parse(fs.readFileSync("../data/friends.json")));
} catch(err) {
// JSON.parse might fail:
next(err);
}
});
// Create new friend:
app.post('/api/friends', function(req, res, next) {
// Option 1, persisted in memory:
friends.push(req.body); // This should be validated properly!
res.json(friends);
// Option 2, loaded and saved everytime:
try {
const friends = JSON.parse(fs.readFileSync("../data/friends.json"));
friends.push(req.body); // This should be validated properly!
fs.writeFileSync("../data/friends.json", JSON.stringify(friends));
res.json(friends);
} catch(err) {
// JSON.parse or fs.writeFileSync might fail:
next(err);
}
});
✨推荐使用body-parser的方式
作为附加建议,即使您会在很多资源中看到body-parser 被用作app.use(bodyParser.json()),the recommended way to use it 也只能将其添加到与其相关的路由中:
快递路线特定
此示例演示了将正文解析器专门添加到需要它们的路由中。一般来说,这是将 body-parser 与 Express 一起使用的最推荐方式。
所以,在你的情况下,你会这样做:
const bodyParser = require("body-parser");
const jsonParser = bodyParser.json();
...
app.post('/api/friends', jsonParser, function(req, res, next) { ... }