gpt4 book ai didi

node.js - 使用 Node.js 发布请求内容

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

我尝试将路由从 Express 应用程序移动到另一个文件,它可以工作,但是当我尝试获取 post 请求的正文时,它是未定义的。

这是 server.js 文件:

var winston = require('winston');
winston.remove(winston.transports.Console);
winston.add(winston.transports.Console, {colorize: true});
winston.add(winston.transports.File, { filename: 'server.err', level: 'error'});
winston.info('Starting server.');

var Firebase = require('firebase-admin');
var connection = require('./connection/firebaseConnection.json');

var express = require('express')
app = express();
var router = require('./srcs/router');
var bodyParser = require('body-parser');

try {
Firebase.initializeApp({
credential: Firebase.credential.cert({
projectId: connection.firebase.project_id,
clientEmail: connection.firebase.client_email,
privateKey: connection.firebase.private_key
}),
databaseURL: 'https://' + connection.firebase.project_id + '.firebaseio.com'
});
winston.info('Connected to Firebase.');
} catch (error) {
winston.error('Could not connect to Firebase : ' + error.code + ' : ' + error.message);
process.exit(1);
}

app.use('/', router);

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use(function(req, res, next) {
var origin = req.headers.origin;
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST', 'GET');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
res.setHeader('Access-Control-Allow-Credentials', true);
return next();
});

var server = app.listen(80, function() {
winston.info('Server listening on port 80.');
});

这是 router.js

var express = require('express');
var router = express.Router();

var winston = require('winston');

router.post('/post', function(req, res) {
console.log(req.body);
});

module.exports = router;

我使用以下命令对其进行了 curl :

curl --data "title=test" http://localhost/post

并且 router.post 被触发,但值未定义。

最佳答案

尝试在路由器中间件调用之前添加 bodyParser 中间件(app.use 调用)。

中间件按照添加顺序运行。您希望 bodyParser 在到达路由器之前执行。

app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

app.use('/', router);

关于node.js - 使用 Node.js 发布请求内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343472/

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