gpt4 book ai didi

javascript - Node.js/Express POST 的 req.body 为空。通过Postman发送POST请求

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

目前我的代码是这样的:

var express = require('express');
var router = express.Router();
var db = require('../helpers/db');

var data = {
"1": 127,
"2": 236,
"3": 348
}

router.get('/', function(req, res, next) {
res.send(data);
});

router.get('/:id', function(req, res, next) {
var key = req.params.id;
res.send({ [key]: data[key] });
});

router.post('/:id', function(req, res, next) {
var id = req.params.id;
console.log(id);
})

我的目标是能够将值从 Postman 发布到 API/values/:id,将该值保存在 id 键下,然后将该“键”:值对保存在数据变量中。不幸的是,当我尝试 POST 任何内容然后使用 req.body 访问它时,我得到 {} 或未定义。

app.js

var routes = require('./routes/');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession({
secret: 'secretText',
saveUninitialized: true,
resave: true
}))
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes.home);
app.use('/values', routes.values);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

module.exports = app;

最佳答案

为此,您需要有expressjs的body-parser插件。

使用npm install --save body-parser安装它,然后像下面一样使用它

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

express()
.use(bodyParser.urlencoded({
extended: true
}))
.use(bodyParser.json())

关于javascript - Node.js/Express POST 的 req.body 为空。通过Postman发送POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47741122/

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