表单POST请求为空/使用NODE未定义

时间:2020-05-20 16:19:01

标签: javascript node.js express

我正在用API设置路由,即使简单的表单似乎也根本不发送任何数据。这是一个简单的html格式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test form</title>
</head>
<body>

<form action="/comments" method="POST">
    <label for="name">Name:</label><br>
    <input type="text" id="name" name="name" value="John"><br>
    <label for="email">Email:</label><br>
    <input type="email" id="email" name="email" value="Doe"><br>
    <label for="comments">Comments:</label><br>
    <input type="text" id="comments" name="comments" value="Some comments"><br><br>
    <input type="submit" value="Submit">
</form>

</body>
</html>

这是在Node中运行的app.js:

const http = require('http');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const morgan = require('morgan')

const hostname = '127.0.0.1';
const port = 3000;

const server = express();
const router = express.Router();

server.use(express.static(__dirname));

server.use(bodyParser.json());
server.use(morgan('dev'));

server.post('/comments', (req, res) => {
  console.log('reached this API call');
  console.log('sending back to homepage');
  console.log('you sent: ' + req.body);
  res.sendFile(path.join(__dirname + '/index.html'));

});

router.get('/', (req, res) => {
  res.sendFile(path.join(__dirname + '/index.html'));
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

这是我单击“提交”按钮后在控制台中看到的内容:

服务器在http://127.0.0.1:3000/上运行
已达到此API调用
发送回首页
您发送了:[object Object]
POST /评论200 2.944毫秒-20059

[对象对象]中没有数据。我尝试访问req.body.name,它是未定义的。我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

要解析application/x-www-form-urlencoded个帖子数据,您需要添加

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

正确记录完整的req.body

const util = require('util');

console.log('you sent: ' + util.inspect(req.body, { showHidden: false, depth: null }));

答案 1 :(得分:0)

我找到了问题的答案。 Vishnu关于使用bodyParser的urlencoded方法是正确的-但真正的问题归因于.htaccess文件。我必须为POST请求添加以下内容:

Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

没有明确允许头方法,GoDaddy共享托管阻止了它们。