gpt4 book ai didi

javascript - 在nodejs中获取request.body值未定义?

转载 作者:行者123 更新时间:2023-12-03 06:00:03 25 4
gpt4 key购买 nike

我的前端代码:

    console.log('In front end ', UserDetails.fname);
$.ajax({
type: 'POST',
data: UserDetails.fname,
url: 'http://localhost:3000',
success: function(data){
console.log('Success!!');
},
error: function(error){
console.log('Error!!');
}
})

在第一个控制台行中,UserDetails.fname 打印正确。但是当我将它发送到后端时,后端将其显示为未定义

我的后端代码

var express = require('express');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var userId = 1;
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'facebook'
});

conn.connect(function(err){
if(!err){
console.log('Database connection success...');
} else {
console.log('Failed to connect to database...')
}

});
var app = express();
// Add headers
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
app.use(bodyParser.text({ type: 'text/html' }));

app.post("/", function(req, res){
console.log(req.headers);
console.log('body: ' + JSON.stringify(req.body));
res.send(req.body);
});
app.listen(3000);

我已经更新了我的代码。但我仍然有同样的问题。

最佳答案

Make sure to put your body-parser code above all the routes

var bodyParser = require('body-parser');

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

关于javascript - 在nodejs中获取request.body值未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39784726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com