Roc*_*tar 6 node.js koa koa-bodyparser
我们使用 navigator.sendBeacon 函数将数据发送到 Koa 服务器,其中我们使用 bodyparser。
如果我们没有将数据包装到表单中,则默认情况下该函数将数据作为请求负载发送。我如何才能访问 Koa 服务器上的这些数据?
例子 -
navigator.sendBeacon('http://localhost:3000/cookies/', 'test=payload')
Run Code Online (Sandbox Code Playgroud)
在服务器上,请求正文为空。
考虑到
Koa 不解析请求体,所以你需要使用koa-bodyparser或koa-body,
koa-bodyparser默认情况下仅json启用form解析,
从您的屏幕截图中可以清楚地看出,将navigator.sendBeacon设置Content-Type为text,
您需要更改Koa服务器代码,以便它解析text数据。
例子:
const Koa = require('koa'),
bodyParser = require('koa-bodyparser'),
app = (module.exports = new Koa());
app.use(bodyParser({ enableTypes: ['json', 'text'] }));
app.use(async (ctx) => {
// ctx.request.body should contain the parsed data.
console.log('Received data:', ctx.request.body);
ctx.body = ctx.request.body;
});
if (!module.parent) app.listen(3000);
Run Code Online (Sandbox Code Playgroud)
测试用
相思木2.7.0,
koa-bodyparser 4.2.1。
| 归档时间: |
|
| 查看次数: |
3512 次 |
| 最近记录: |