将bodyParser urlencoded设置为false扩展后,req.body返回未定义的

时间:2018-07-09 14:46:11

标签: node.js express body-parser

我是nodejs的新手。我试图创建简单的聊天应用程序。即使在设置我的身体解析器 urlencoded({extented:false})之后,app.post中的 req.body 似乎仍未返回。有人可以引导我完成此操作吗? !..提前谢谢

这是我的服务器端代码server.js:

var express = require('express')
 var bodyParser = require('body-parser')
 var app = express()

app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json())
app.use(express.static(__dirname))

var messages = [
{name:'Brue',message:'Hello Diana'},
{name:'Diana', message:'Hey Bruce.'} ]

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

app.post('/messages', (req,res) => {
messages.push(req.body)
res.sendStatus(200)})

var server = app.listen(8080, (err,data) => {
console.log('The server runs on the port:', server.address().port) })

这是我的客户端代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Message App</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
</head>
<body>
<div class="container">
<br>
<div class="jumbotron"> 

    <h1 class="display-4"> Send Message  </h1>
    <br>
    <input class="form-control" type="text" placeholder="Name">
    <br>
    <textarea placeholder = "Message" class="form-control" id="mesage" cols="30" rows="10"></textarea>
    <br>
    <button id = "send" class="btn btn-success"> Send</button>
    </div>
<div id="messages"></div>
</div>

<script>
$(() => {
$('#send').click(() => {
    var message = { name: $("#name").val(), message: $("#message").val()}
    postMessage(message)

})
getMessages() })

function addMessages(message){
$("#messages").append(`<h4>${message.name}</h4> <p> ${message.message}  </p>`) }

function getMessages(){
$.get('http://localhost:8080/messages',(data) => {
    data.forEach(addMessages); })  } 

function postMessage(message){
$.post('http://localhost:8080/messages', message)
}

1 个答案:

答案 0 :(得分:-1)

在您的html中,您拼错了textarea的ID。它是id="mesage"而不是带有两个's的id="message"。而且,您永远不会设置#name的ID。修复这些。

<input class="form-control" id="name" type="text" placeholder="Name">

<textarea placeholder="Message" class="form-control" id="message" cols="30" rows="10"></textarea>

确保您将发送的变量有效。我建议您在这种情况下使用chrome调试器。