简体   繁体   English

app.use(express.raw()) 在 Express.js 中不起作用

[英]app.use(express.raw()) not working in Express.js

I am making an Express application that takes in (binary) post data.我正在制作一个接收(二进制)发布数据的 Express 应用程序。 Here is my code below.下面是我的代码。

Server-side:服务器端:

var express = require('express');
var app = express();
var PORT = 3000;

app.use(express.raw());
    
app.post('/', function(req, res) {
    console.log(req.body);
    res.end();
});

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.listen(PORT, function() {
    console.log("Server listening on port", PORT);
});

index.html:索引.html:

<script>
  fetch("/", {
    method: "POST",
    body: "hello world",
  });
</script>

However, when I run this code, when logging the request body, it logs an empty object.但是,当我运行此代码时,在记录请求正文时,它会记录一个空对象。 And when I looked at the documentation, it says that the request body will be an empty object if there was no body to parse.当我查看文档时,它说如果没有要解析的主体,请求主体将是一个空对象。 But I had a body in the request.但我在请求中有一个正文。 What am I doing wrong here?我在这里做错了什么?

For express.raw() to parse, add "Content-Type": "application/octet-stream" inside headers in your fetch() .要解析express.raw() ,请在fetch()headers中添加"Content-Type": "application/octet-stream" Like so:像这样:

fetch("/", {
  method: "POST",
  body: "hello world",
  headers: {
    "Content-Type": "application/octet-stream",
  },
});

express.raw() only works if you set your Content-Type header in your fetch to `application/octet stream. express.raw()仅在您将 fetch 中的Content-Type标头设置为 `application/octet 流时才有效。 So your new fetch method would look like this.所以你的新 fetch 方法看起来像这样。

fetch("/", {
    method: "POST",
    body: "hello world",
    headers: {
      "Content-Type": "application/octet-stream"
    }
});

But what if you don't want the content type to be application/octet-stream ?但是,如果您不希望内容类型为application/octet-stream怎么办? In this case, you can specify in the express.raw() options that the content type to parse the body can be any type.在这种情况下,您可以在express.raw()选项中指定解析正文的内容类型可以是任何类型。 How to do this?这个怎么做? Replace this:替换这个:

app.use(express.raw());

With this:有了这个:

app.use(express.raw({type: '*/*'}));

The type option is the needed content type for body-parser to parse the body, and the */* means that any content type will be accepted. type选项是body-parser解析正文所需的内容类型, */*表示将接受任何内容类型。

将此用于您的用例app.use(express.text());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM