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

时间:2016-08-28 02:32:13

标签: javascript node.js express fetch

我正在尝试使用fetch()使用POST方法将JSON发送回我的快速应用程序。这是我的代码:

 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得到了未定义的内容,所以我不确定我是否正确获取了数据。我在这里错过了什么?我的取物 - 身体不正确吗?这就是我的猜测但是我无法弄清楚正确的语法。

// *********** EDIT-SOLUTION ************ //

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

4 个答案:

答案 0 :(得分:1)

通常情况下,您必须像流一样从from Tkinter import * from collections import Counter import string def let_freq(): user_input = (e.get().lower()).translate(None, string.whitespace) res = "" value_alphabet = Counter(user_input) v = StringVar() label = Label(root, text="Result:", textvariable=v).grid(ipadx=5,ipady=5) for key, value in value_alphabet.items(): print key, value/float(len(user_input))*100, '%' res += '\n'+key+'-'+`value/float(len(user_input))*100`+'%' v.set(res) root = Tk() e = Entry(root); assert isinstance(e, object); e.grid(ipadx=5, ipady=5) button = Button(root, command=let_freq, width=16).grid(ipadx=5, ipady=5) root.mainloop() 读取内容。像这样:

req

更好的解决方案是使用body-parser middleware

答案 1 :(得分:1)

最好将post-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...});

答案 2 :(得分:1)

略有不同的解决方案对我有用。 body-parser does not handle multipart/form-data bodies

客户端 #B1 { margin: 50px; margin-top: 50px; margin-bottom: 50px; flex: 1 1 auto; padding: 20px; border: 2px solid #f7f7f7; text-align: center; text-transform: uppercase; position: relative; overflow:hidden; transition: .3s; &:after { position: absolute; transition: .3s; content: ''; width: 0; left: 0; bottom: 0; height: 3px; background: #f7f7f7; } } #B1:hover::after { width:100% } #B2:hover::after { width:100% } 调用发送数据以表达:

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 }) 侦听app并将其解析为json:

application/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) // ... }) 是json。

答案 3 :(得分:-1)

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