Next.js form 表单提交到服务器后 body 内无数据?

新手上路,请多包涵

如题

//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 正常。望指导!

阅读 3.6k
1 个回答
新手上路,请多包涵

纠结了很久,偶然查询表单的资料找到了突破口。还是由于自己知识不过关造成的。

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

描述
application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
text/plain 空格转换为 "+" 加号,但不对特殊字符编码。

当然,表单是何如编码的,服务器处理的请求的时候就需要使用相应的解析器对其进行解码。在这个案例中,需要使用 urlencoded 的解析器:

const urlencodedParser  = bodyParser.urlencoded();


server.post('/test', urlencodedParser, (req, res, next) => {
      console.log(req.body);
      next()
  })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进