gpt4 book ai didi

node.js - req.body 未返回提交的数据

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:12 25 4
gpt4 key购买 nike

我正在尝试学习 MEAN 堆栈,但遇到了一个问题。我开发了小型 Express 应用程序。但这个我想不通。

我正在使用 Angular Http 服务发布表单数据。

使用post方法发布数据的服务代码。

createUser(user: User): Observable<User> {
const submittedUser = JSON.stringify(user);
console.log("submitted:", submittedUser);
const headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
const options = new RequestOptions({headers: headers});
return this.http.post('http://localhost:3000/user/create', submittedUser, options)
.map((response: Response) => {response.json()})
.catch((error:Response) => Observable.throw(error.json()));

}

在服务器端,我有 app.js 和一个路由器文件。

'use strict';

var express = require('express');
var path = require('path');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var userRoutes = require('./routes/userRoutes');

var app = express();
mongoose.connect('mongodb://localhost/go-social');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});

app.use('/user', userRoutes);

app.use(function(req, res, next) {
return res.render('error');
});

app.listen(3000, function() {
console.log("App listening on port 3000");
})

这是路由器文件。 userRoutes.js

enter var express = require('express');
var router = express.Router();
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var User = require('../models/user');
router.post('/create', function (req, res) {

console.log(req.body);
var user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
password: req.body.password
});
user.save(function(err, result) {
if(err) next(err);
res.status(201).json({
message: "Your account has been created successfully",
obj: result
});
});
});

当我使用 Postman 时,它可以工作,但它不适用于 Http 服务。我在控制台中将 req.body 作为对象与我提交的对象一起获取。

{ '{"firstName":"Myname","lastName":"sadf","email":"abc@gmail.com","password":"awe"}': '' }

最佳答案

改变

来自

const headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' })

const headers = new Headers ({  'Content-Type': 'application/json' })

关于node.js - req.body 未返回提交的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757317/

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