我正在構建一個React和Node應用程式,我試圖將資料從React發送到Node并在控制臺中列印出來。以下是我的代碼:
React代碼:
import React, { Component } from 'react;
import axios from 'axios';
class Test extends React.Component{
constructor(props) {
super(props)。
this.state = { name: 'Serban' };
this.tick = this。 tick.bind(this)。
}
tick() {
console.log(this.state.name) 。
const article = { n: this.state.name };
axios.post('http://localhost:3001/api'/span>, article)
}
componentDidMount(){
//使用axios的簡單POST請求與JSON主體。
}
render() {
return(
<div>
<button onClick={this. tick}>Send</button>
</div>
);
}
}
export default Test;
節點代碼:
const express = require("express") 。
const router = express.Router();
const axios = require('axios'/span>);
const cors = require("cors") 。
const PORT = process.env.PORT || 3001;
const app = express()。
app.use(cors()
app.post('/api'/span>, function(req, res) {
var nume = req.body.n。
console.log("Salut" nume)。
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`) 。
});
我得到了這個錯誤:
Server listening on 3001>
TypeError。無法讀取屬性'n' of undefined
在C。
eact-efacturaserverindex.js:16:23。
在Layer.handle [as handle_request] (C:
eact-
控制元件
編碼
outerlayer.js:95:5)
在 next (C:
實驗------efactura
ode_modulesexpresslib
外部
oute.js:137:13)
在Route.dispatch(C:
控制元件
ode_modulesexpresslib
外部
oute.js:112:3)
在Layer.handle [as handle_request] (C:
eact-
控制元件
編碼
outerlayer.js:95:5)
在C。
實驗------efactura
ode_modulesexpresslib
outerindex.js:281:22。
在Function.process_params (C:
eact-
流程
ode_modulesexpresslib
outerindex.js:335:12)
在 next (C:
實驗------efactura
ode_modulesexpresslib
outerindex.js:275:10)
在cors (C:
實驗結果
ode_modulescorslibindex.js:188:7)
在C。
實驗------EFACTURA
ode_modulescorslibindex.js:224:17。
我做錯了什么?我已經嘗試了我在谷歌上搜索的各種東西,但都沒有用。似乎它能從React完成請求,但它沒有發送值。為什么它不發送值?
uj5u.com熱心網友回復:
奇怪的是,Node并不自動使req.body可用。你必須手動添加一個中間件來決議從瀏覽器傳入的資料,并構建req.body,然后可以使用。多年來,我們一直使用body-parser模塊,現在Express 4.16以上版本可以直接使用app.use(express.json());
關于這一點,有一些有趣的閱讀。https://medium.com/@mmajdanski/express-body-parser-and-why-may-not-need-it-335803cd048c
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/310205.html
標籤:
