使用Fetch将JSON放入文档主体 - Javascript

3
我将为您翻译以下内容:

我正在尝试使用fetch()方法通过POST方式将JSON发送回我的express应用程序。以下是我的代码:

 fetch('https://development.c9users.io/canadmin',{
                method:'POST',
                body:JSON.stringify({
                    csv: results
                })

这是我在Express中的提交方法:

app.post("/canadmin", function(req,res){
var data = req.body.csv;
console.log(data);
//  r.db('cansliming').table('daily').insert( r.json(data) ).run(err, );
res.redirect("canadmin");
});

我在控制台中得到了“未定义”的输出,因此我不确定我是否正确地获取了我的数据。我错过了什么?我的fetch-body有误吗?这就是我的猜测,然而我无法找出正确的语法。

// ***********编辑-解决方案************ //

我去参加了一个Javascript聚会,一个名叫Alex的好人找到了解决方案。标题是不正确的,我们还添加了模式:

fetch('/saveRecords',{
                headers: {
                        //This is the line we need for sending this data
                      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
                },
                mode : 'no-cors',
                method:'POST',
                //This is the line we need actually send the JSON data
                body: JSON.stringify(results)
             }) //End fetch()

做完这个之后,我能够在Express的req.body中看到它!希望这能帮助到某些人。

console.log(req.body) - enRaiser
我做了那个,但它只是返回了{ }。 - illcrx
你在请求时将 body 转换为 String 是否有特别的理由? - abdulbarik
4个回答

2

对我来说,稍微有些不同的解决方案起了作用。body-parser 无法处理multipart/form-data格式的请求体

客户端使用fetch调用将数据发送到express:

fetch('api/users', {
  headers: { 'Content-Type': 'application/json' }, // tells the server we have json
  method:'PUT', // can be POST
  body: JSON.stringify(results), // json is sent to the server as text
})

服务器端的Express app 监听application/json并将其解析为JSON:

const express = require('express')
const app = express()

// parse application/json
app.use(bodyParser.json())

设置完bodyParser后,我定义了一个express中间件函数。

app.put('/api/:collection', (req, res) => {
  logger.log('put', req.body)
  // ...
})

req.body 是 JSON 格式的。


考虑到 headers = new Headers({'Content...:'application/json', ...other headers...}),我遇到了一些问题,具体原因我没有花时间去弄清楚,但是我成功地将现有的头部属性传递给构造函数并覆盖了原始头部属性(进入API)。 - jimmont

1
通常情况下,您需要像读取流一样从req中读取。类似这样的代码:
var body = '';
req.on('data', function (chunk) {
  body += chunk;
});

req.on('end', function () {
  console.log(JSON.parse(body));
});

更好的解决方案是使用 body-parser中间件

我实际上已经有了bodyParser,但我没有想到用它来做这件事。我应该如何在bodyParser中实现呢? - illcrx
@illcrx 我已经链接了说明文档。app.use(bodyParser.json()). - Brad
如果我刚才给你的代码不起作用,你应该发布一个新问题。 - Brad
我认为答案应该与问题相匹配,而不是反过来。我为什么要重新发布同样的问题呢? - illcrx
@illcrx,你现在提出了一个不同的问题。你一开始问的是如何处理Express中的POST请求体。现在你正在询问如何使用body-parser中间件,而我在评论和文档中给你的代码并没有起作用。这是一个完全不同的问题,需要展示不同的代码。 - Brad

1

使用body-parser中间件进行post方法会更好。

例如伪代码(ES6格式):

包含body-parser:

import bodyParser from 'body-parser';
const urlEncode = bodyParser.urlencoded({extended: false});

现在,将它用于 API 的 POST 请求,就像这样:

app.post('/something_url', urlEncode, (req, res) => { ...your code here...});

问题:我正在使用类似的东西,我有这个:var bodyParser = require("body-parser");......................app.post("/canadmin", bodyParser, function(req,res){ var data = req.body; console.log(data); // r.db('cansliming').table('daily').insert( r.json(data) ).run(err, ); res.redirect("canadmin"); }); - illcrx

-1

我也有同样的问题。如何调用fetch。 我不知道它是否工作,因此没有得到任何更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接