2017-08-26 28 views
0

我從我的ReactJS客戶端發佈一些數據到Express服務器,但似乎我無法訪問req.body中的數據....我是發送一個JSON對象是這樣的:ExpressJs | req.body不是空的,但不能訪問數據

var url = 'http://localhost:8000/scrape/'; 
    const {main} = getState() 

    const info = { name : main.title, items : main.list} 
    var options = { 
     url: url, 
     method: 'POST', 
     body : JSON.stringify(info), 
     json: true, 
     headers : { 
     'Content-Type': 'application/x-www-form-urlencoded' 
     } 
    }; 


    Request(options, (error, response, data) => { 
     // !error ? dispatch(setSearchResults(JSON.parse(data))) : dispatch(setError(error)); 
    }); 

,當我在快遞CONSOLE.LOG(req.body),我收到這樣的:

{ '{"name":"test","items":': { '{"url":"test","code":"ING"},{"url":"test","code":"KIN"},{"url":"test","code":"GAO"}': '' } } 

在我快我用bodyParser

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

我試過使用JSON.stringify(req.body)和JSON.parse(req.body),但都沒有成功,有什麼建議嗎?

+0

你爲什麼讓'內容Type'爲'應用程序/ x-WWW- form-urlencoded'而POST正文是JSON? – shaochuancs

+0

是的,我注意到,當我查看代碼時,似乎當我嘗試應用程序/ json時,req.body將在Express中保持emty –

+0

代碼中的「Request」模塊是什麼?另外,您是否檢查過瀏覽器DevTool中的HTTP網絡 - 在Content-Type爲application/json時,客戶端是否發送了JSON主體? – shaochuancs

回答

0

這是解決方案: How to allow CORS?

而且我這是怎麼做出正確的JSON請求:

var options = { 
     uri: url, 
     method: 'POST', 
     json: { 
     "name": main.tile, "items" : main.list 
     } 
    }; 

    Request(options, (error, response, data) => { 

    }); 
相關問題