鍍金池/ 問答/HTML/ Next.js form 表單提交到服務(wù)器后 body 內(nèi)無數(shù)據(jù)?

Next.js form 表單提交到服務(wù)器后 body 內(nèi)無數(shù)據(jù)?

如題

//pages/index.js
const Index = () => (
    <div>
        <form action='/test'  method='Post'>
            <input type='text' name='name'/>
            <input type='submit' value='submit'/>
        </form>
    </div>
);

export default Index;
const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

const bodyParser = require('body-parser');
const jsonParser = bodyParser.json();

app.prepare()
.then(() => {
  const server = express()
  // 此處req.body 為 {}
  server.post('/test', jsonParser, (req, res, next) => {
      console.log(req.body);
      next()
  })
    server.post('*', jsonParser, (req, res, next) => {
      console.log("_____");
      next();
  });


  server.get('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(3000, (err) => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})
.catch((ex) => {
  console.error(ex.stack)
  process.exit(1)
})

我嘗試用 ajax 提交,ajax 正常。望指導!

回答
編輯回答
詆毀你

糾結(jié)了很久,偶然查詢表單的資料找到了突破口。還是由于自己知識不過關(guān)造成的。

enctype 屬性規(guī)定在發(fā)送到服務(wù)器之前應(yīng)該如何對表單數(shù)據(jù)進行編碼。

默認地,表單數(shù)據(jù)會編碼為 "application/x-www-form-urlencoded"。就是說,在發(fā)送到服務(wù)器之前,所有字符都會進行編碼(空格轉(zhuǎn)換為 "+" 加號,特殊符號轉(zhuǎn)換為 ASCII HEX 值)。

描述
application/x-www-form-urlencoded 在發(fā)送前編碼所有字符(默認)
multipart/form-data 不對字符編碼。在使用包含文件上傳控件的表單時,必須使用該值。
text/plain 空格轉(zhuǎn)換為 "+" 加號,但不對特殊字符編碼。

當然,表單是何如編碼的,服務(wù)器處理的請求的時候就需要使用相應(yīng)的解析器對其進行解碼。在這個案例中,需要使用 urlencoded 的解析器:

const urlencodedParser  = bodyParser.urlencoded();


server.post('/test', urlencodedParser, (req, res, next) => {
      console.log(req.body);
      next()
  })
2018年2月7日 07:06