鍍金池/ 問答/數(shù)據(jù)庫  HTML/ nodejs 怎么解析post進(jìn)來的json數(shù)據(jù)?

nodejs 怎么解析post進(jìn)來的json數(shù)據(jù)?

問題描述

通過post提交數(shù)據(jù),然后node解析后,使用MongoDB插入到集合。
前端要怎么編碼這些數(shù)據(jù),然后再通過nodejs正確的解析出來?

問題出現(xiàn)的環(huán)境背景及自己嘗試過哪些方法

使用的是axios進(jìn)行post請(qǐng)求的,一開始在前端使用JSON.stringify()但是不行,nodejs解析出來是這樣的:

data = [{'goodsId':1,'goodsName':'雞米花','price':10}] ==> {'{'goodsId':1,'goodsName':'雞米花','price':10}': ''}

nodejs解析后,把我的數(shù)據(jù)直接變成屬性了……。
還試過直接post數(shù)據(jù)過去后端,但后端拿到的是[obejct object]
通過搜索后,我試了QS模塊,使用了Qs.stringify(data),后端終于拿到數(shù)據(jù)了,但是只能拿一條。如果我試圖在data里面添加多一個(gè)對(duì)象,它無法正確的解析2條數(shù)據(jù),會(huì)把同樣屬性的疊加進(jìn)去。我還是貼圖和貼代碼吧!

你期待的結(jié)果是什么?實(shí)際看到的錯(cuò)誤信息又是什么?

nodejs代碼

const express = require('express');
const app =  express();
const fs = require('fs');
const bodyParser = require("body-parser");
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost:27017/";

app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());
//設(shè)置跨域訪問
app.all('*',function(req,res,next) {
    res.header('Access-Control-Allow-Origin', '*'); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
})

//食物套餐請(qǐng)求
app.get('/foodmeal',function(req,res) {
    //讀取文件
    fs.readFile('foodmeal.json',function(err,data){
        if(err) return console.error(err);
        //響應(yīng)http請(qǐng)求
        res.send(data);
    });
});
//食物詳情請(qǐng)求
app.get('/foods',function(req,res) {
    //讀取文件
    fs.readFile('foods.json',function(err,data) {
        if(err) return console.error(err);
        res.send(data);
    });
});

app.post("/settle_post", function (req, res) {
    //在這里面來操作MongoDB數(shù)據(jù)庫
    MongoClient.connect(url,function(err,db) {
        if(err) throw err;
        //鏈接數(shù)據(jù)庫
        let dbo = db.db('foodmeal');
        //要插入的數(shù)據(jù)
        console.log(req.body);    
        let myobj = [req.body];
        // console.log(myobj);
        //鏈接集合,并且插入數(shù)據(jù)
        dbo.collection('food').insertMany(myobj,function(err,res){
            if(err) throw err;
            console.log('插入了' + res.insertedCount);
            db.close();
        });
    })

    // console.log(req.body);
    res.send();
});


app.listen(3000);
console.log('listening on port 3000...');
{ goodsId: '1',
  goodsName: [ '香辣雞腿堡', '田園雞腿堡' ],
  price: [ '18', '15' ],
  count: [ '1,goodsId=2', '1' ] }
//這里是添加了兩條數(shù)據(jù)后顯示的解析出來的結(jié)果,只有g(shù)oodsid沒被疊加,但不管有沒疊加,我希望的是兩條數(shù)據(jù),然后可以使用MongoDB進(jìn)行插入

前端代碼

            let data = [];
            //this.tableData ==>需要提交的數(shù)據(jù)
            this.tableData.forEach((item,i) => {
                data[i] =  Qs.stringify(item);
            });

            // let data = Qs.stringify(this.tableData[0]);一條數(shù)據(jù)的話沒問題
            console.log(data);
            axios({
                url:'http://localhost:3000/settle_post',
                method:'post',
                data:data,
                transformRequest: [function(data){
                    return data;
                }],
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })

因?yàn)閯倢W(xué)的node沒兩天,有些東西不清楚,百度了各種方法還是未得結(jié)果,只能求助各位大佬啦!因?yàn)樾〉苤R(shí)比較單薄,如果還需要提供什么東西,請(qǐng)?jiān)谠u(píng)論里面提醒。謝謝
ps:(目前想到個(gè)很浪費(fèi)的方法,循環(huán)數(shù)據(jù),然后每條數(shù)據(jù)進(jìn)行一次post請(qǐng)求- -)

回答
編輯回答
舊言

application/x-www-form-urlencoded改成application/json,你得告訴服務(wù)器數(shù)據(jù)是json格式的

2017年2月22日 21:47
編輯回答
笨笨噠

nodejs中用 body-parse這個(gè)模塊處理一下接收的數(shù)據(jù)。

2018年1月4日 19:42
編輯回答
爆扎

前端代碼改成:


            axios({
                url:'http://localhost:3000/settle_post',
                method:'post',
                data:JSON.stringify(tableData),
                headers: {
                    'Content-Type': 'application/json'
                }
            })
2017年7月6日 03:50
編輯回答
青瓷

后端JSON.stringify(你的json)查看數(shù)據(jù)。
后端for循環(huán)你的JSON對(duì)象屬性讀取數(shù)據(jù),或者直接通過obj[name]讀取對(duì)象數(shù)據(jù)

2018年5月30日 09:49
編輯回答
風(fēng)清揚(yáng)

提交json應(yīng)該用application/json而不是application/x-www-form-urlencoded。application/x-www-form-urlencoded會(huì)把json數(shù)據(jù)轉(zhuǎn)化為goodsId='1'&goodsName='香辣雞腿堡,田園雞腿堡'body里面。

2018年4月30日 10:19