我在我的应用程序中使用express和body-parser.
app.use(bodyParser.urlencoded({ extended: false }));
Run Code Online (Sandbox Code Playgroud)
但是,快递4.0中"延伸"的含义是什么?
我找到了这个
extended - parse extended syntax with the qs module.
Run Code Online (Sandbox Code Playgroud)
但是,我仍然无法理解其含义.
我正在使用新的浏览器功能(navigator.sendBeacon)将异步数据发送到node.js服务器.
但我无法在节点服务器上收到它.那么任何人都可以告诉我如何在节点服务器上接收sendBeacon发布的数据.
节点服务器代码是:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// set cross origin header to allow cross-origin request.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json());
app.post('/',function(req,res){
console.log('i got the request',req.body)
});
var server = app.listen(3000, function() {
console.log('Express is listening to http://localhost:3000');
});
Run Code Online (Sandbox Code Playgroud)
客户端代码
navigator.sendBeacon('http://localhost:3000/','{"a":9}')
Run Code Online (Sandbox Code Playgroud) 如何访问 API 中的文件?
我阅读了其他解决方案,它们都需要 npm 包来解决这个问题。我想明白为什么我不能做到香草。另外,答案很旧,建议使用 body-parser,它现在与 Express 捆绑在一起。
我希望解决方案是普通 JS,以便更好地理解该过程。
客户
async function uploadFile(file) {
let formData = new FormData();
formData.append("file", file);
let res = await fetchPostFile("/api/files", formData);
}
Run Code Online (Sandbox Code Playgroud)
拿来
export async function fetchPostFile(url, formData) {
try {
let result = await (
await fetch(url, {
method: "POST",
withCredentials: true,
credentials: "include",
headers: {
Authorization: localStorage.getItem("token"),
Accept: "application/json",
"Content-type": "multipart/form-data",
},
body: formData,
})
).json();
return result;
} catch (err) {
return err;
}
}
Run Code Online (Sandbox Code Playgroud)
应用程序编程接口
router.post("/api/files", async function …Run Code Online (Sandbox Code Playgroud) 我正在阅读《使用Node和Express进行Web开发》一书,遇到了麻烦。
我被指示将以下内容放入我的应用程序文件,但它似乎body-parser已被弃用,将无法使用。如何获得相同的功能?
这是我当前的代码:
app.use(require('body-parser')());
app.get('/newsletter', function(req, res){
// we will learn about CSRF later...for now, we just
// provide a dummy value
res.render('newsletter', { csrf: 'CSRF token goes here' });
});
app.post('/process', function(req, res){
console.log('Form (from querystring): ' + req.query.form);
console.log('CSRF token (from hidden form field): ' + req.body._csrf);
console.log('Name (from visible form field): ' + req.body.name);
console.log('Email (from visible form field): ' + req.body.email); res.redirect(303, '/thank-you');
});
Run Code Online (Sandbox Code Playgroud)