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

Using Fetch to put JSON in body of document - Javascript

本文关键字:主体 -Javascript 文档 Fetch JSON 使用      更新时间:2023-09-26

我正在尝试使用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");
});

我在console.log中未定义,所以我不确定我是否正确地获取了数据。我在这里错过了什么?我的提取体不正确吗?这就是我的猜测,但我无法找出正确的语法。

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

我参加了一个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中看到它!我希望这能帮助到别人。

我使用的解决方案略有不同。body解析器不处理multipart/form-data bodies

客户端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之后,我定义了一个快速中间件功能

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

CCD_ 6是json。

通常,您必须像流一样从req中读取。类似这样的东西:

var body = '';
req.on('data', function (chunk) {
  body += chunk;
});
req.on('end', function () {
  console.log(JSON.parse(body));
});

更好的解决方案是使用body解析器中间件。

post方法最好使用body解析器中间件。

例如伪代码:(ES6格式(

包括主体解析器:

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

现在,在api post请求中使用它,如下所示:

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

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