簡體   English   中英

req.body是空的,我無法弄清楚為什么

[英]req.body is empty and I can't figure out why

我是表達和節點的新手,我正在嘗試向我的服務器發布一個axios帖子,但是當我在節點中的console.log時,req.body將變空。 誰知道我做錯了什么? 我是控制台記錄並發送給郵遞員。

這是server.js

const app = require('express')()
const bodyParser = require('body-parser');



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

app.get('/', (req, res) => {

  res.send('hello')
})

const port = 4444;

app.post('/send', (req, res) => {
      console.log('body: ', req.body)
      res.status(200).send(req.body)
});



app.listen(port, () => {
  console.log('We are live on port 4444');
});

我的axios電話

export default class Form extends Component {
     constructor(props) {
         super(props) 
         this.state = {
            name: 'kaleb',
            message: '',
            email: '',
            number: '',
            sent: false
         }




     }

     handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value
        })

     }

     handleSubmit = () => {
         axios.post("/send", {name: this.state.name}).then(() => {
             console.log(this.state.name)
         })


     }

在server.js中試試這個:

    app.use(bodyParser.json());
    app.use(bodyParser.json({type: 'application/*+json'}));
    app.use(bodyParser.urlencoded({extended: false}));//or true whatever you need

axios電話:

    axios({method:'post',url:'/send',data:{name:this.state.name}})
      .then(console.log(this.state.name));

嘗試將url作為http://localhost:4444/send到你的axios調用中:

 handleSubmit = () => {
         axios.post("http://localhost:4444/send", {name: this.state.name}).then(() => {
             console.log(this.state.name)
         })

好的,這是我在閱讀完所有上述評論后的想法。

  1. 你說,當你通過郵遞員發送請求時,它是console.log一個空的req.body。 所以你的網址沒問題。 它正在改正路由器。 郵差有3種內容類型。 只需選擇“X-www-form-urlencoded”並再次發送請求即可。 它應該工作。
  2. 在你的組件中,你說在提交后沒有任何事情發生。 最有可能的問題應該是你的網址。 您的后端服務器在端口4444上運行並且通常會在PORT 3000上運行應用程序。因此,當您調用axios.post('/ send')時,它實際上發送到localhost:3000/server而不是localhost:4444/server 現在它不會起作用。 您需要設置代理以避免此問題。 這是https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development的方式。 或者您可以使用axios.post('http://localhost:4444/server')

注意: 如果您使用axios.post('http://localhost:4444/server') ,您將面臨cors問題。 使用它來消除該問題https://www.npmjs.com/package/cors

這通常是通過將urlencoded擴展名設置為true引起的,請嘗試以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM