我正在使用express 4.0,我知道主体解析器已经从express核心中取出,我正在使用推荐的替换,但我正在获得
bodyParser:使用单独的json/urlencoded中间件server.js:15:12
对扩展解析显式指定"extended: true" node_modules/ Body-parser /index.js:74:29
我在哪里可以找到这些所谓的中间件?或者我不应该得到这个错误?
var express = require('express');
var server = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('./config/passport');
var routes = require('./routes');
mongoose.connect('mongodb://localhost/myapp', function(err) {
if(err) throw err;
});
server.set('view engine', 'jade');
server.set('views', __dirname + '/views');
server.use(bodyParser());
server.use(passport.initialize());
// Application Level Routes
routes(server, passport);
server.use(express.static(__dirname + '/public'));
server.listen(3000);
不要使用体解析器
如果你使用的是Express 4.16+,你可以用Express这样做:
app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads
你现在可以使用npm uninstall body-parser卸载body-parser
要获得POST内容,可以使用req.body
app.post("/yourpath", (req, res)=>{
var postData = req.body;
//Or if this doesn't work
var postData = JSON.parse(req.body);
});
我希望这对你们有帮助
检查这个答案
条带webhook错误:没有找到匹配有效载荷的期望签名
// Use JSON parser for all non-webhook routes
app.use((req, res, next) => {
if (req.originalUrl === '/webhook') {
next();
} else {
express.json()(req, res, next);
}
});
// Stripe requires the raw body to construct the event
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const sig = req.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, webhookSecret);
} catch (err) {
// On error, log and return the error message
console.log(`❌ Error message: ${err.message}`);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
// Successfully constructed event
console.log('✅ Success:', event.id);
// Return a response to acknowledge receipt of the event
res.json({received: true});
});