gpt4 book ai didi

javascript - 使用 Fetch 将 JSON 放入文档正文中 - Javascript

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:24 24 4
gpt4 key购买 nike

我正在尝试使用 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 得到了未定义的信息,所以我不确定我是否正确地获取了我的数据。我在这里错过了什么?我的 fetch - body 不正确吗?这就是我的猜测,但是我无法找出正确的语法。

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

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

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 中看到它!我希望这可以帮助别人。

最佳答案

略有不同的解决方案对我有用。正文解析器 does not handle multipart/form-data bodies

客户端fetch调用发送数据表示:

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。

关于javascript - 使用 Fetch 将 JSON 放入文档正文中 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com