gpt4 book ai didi

javascript - 使用 ExpressJS POST 请求为空

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

当我向服务器的路由发出 POST 请求时,request.body 为空。我正在使用主体解析器来获取 JSON 数据。我做错了什么?

_saveTicket 函数上,我有 console.log 来显示所有正文请求参数。当我执行 POST 请求时,request.body 为空。

我需要什么来自动解析它?

server.js

/**
* Declaration
**/
var express = require('express'),
database = require('./config/database.js'),
morgan = require('morgan'),
port = 2559,
bodyPar = require('body-parser'),
methodOv = require('method-override'),
mongoose = require('mongoose'),
fsr = require('file-stream-rotator'),
logDirectory = __dirname + '/log',
favicon = require ('serve-favicon');
app = express();

/**
* DB Connection
**/
mongoose.connect(database.mongo);

/**
* Api definition
**/
var accessLogStream = fsr.getStream({
date_format: 'YYYYMMDD',
filename: logDirectory + '/access-%DATE%.log',
frequency: 'daily',
verbose: false
})

app.use(express.static(__dirname + '/public'));
app.use(morgan('combined', {stream: accessLogStream}));
app.use(bodyPar.urlencoded({'extended':'true'}));
app.use(bodyPar.json());
app.use(bodyPar.json({ type: 'application/vnd.api+json' }));
app.use(methodOv('X-HTTP-Method-Override'));
app.use(favicon(__dirname + '/public/images/favicon.ico'));

/**
* Routes section
**/
require('./routes/ticket.js')(app);

/**
* Starting server
**/
app.listen (port)
console.log ("Listening on port: " + port);

model/ticket.js

var mongoose = require('mongoose');

var TicketSchema = new mongoose.Schema({
title: String,
description: String
}, {versionKey: false});

module.exports = mongoose.model('Ticket', TicketSchema, 'Ticket');

routes/ticket.js

var Ticket = require('../models/ticket');

module.exports = function(app){

_getAllTickets = function(req, res){
var query = Ticket.find().lean();

query.exec(function(err, lst){
if(err)
res.send(err);

res.json(lst);
});
};

_saveTicket = function(req, res){
console.log(req.body);

var tckt = new Ticket({
title: req.body.title,
description: req.body.description
});

tckt.save(function(err){
if(!err)
console.log('Ticket creation successful. ');
else
console.log('ERROR: ' + err);
});

res.send(tckt);
};

app.get('/api/tickets/', _getAllTickets);
app.post('/api/tickets/', _saveTicket);
}

最佳答案

确保 HTTP 请求的 Content-Type header 设置为 application/jsonx-www-form-urlencoded基于您的 body-parser 中间件定义。我的猜测是,它现在不会出现,因为这些 Content-Type

关于javascript - 使用 ExpressJS POST 请求为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022223/

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