对于my应用,我编写了一个简单的服务客户端模块,将http请求发送到我的api端点,用于CRUD操作,我现在正在发送表单数据作为带有api端点的查询字符串(我认为这不是正确的方法)。在api中,为了使 POSTman 兼容,我总是检查请求体是否未定义否则我从查询字符串中获取表单数据。到目前为止一切都很好,一切正常,但我需要的是,我想将表单数据作为请求主体传递给http请求的选项。
我已经通过node.js documentation获取http请求和许多其他相关文章,但没有找到符合我要求的确切解决方案。所以,请帮帮我。
以下是我的应用程序中的一些源代码: -
// Default controller
var Services = require('./service-client');
function add_place(req, res){
var thisRes = res;
var apiClient = new Services(req, '/api/places');
if(req.method != 'GET'){
apiClient.post(req.body, function(err, res){
console.log(res);
thisRes.redirect('/');
});
}else{
res.render('add-place', {
title: 'Add Express'
});
}
}
var http = require('http');
var querystring = require('querystring');
Services.prototype.post = function(form_data, callback){
var post_data = querystring.stringify(form_data);
this.description.path = this.apiURL+'?'+post_data;
this.description.method = 'POST';
var options = this.description;
var temp = http.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
callback(null, chunk);
});
});
temp.end();
};
var Place = require('../models/place');
require('../db-config')(app);
router.post('/', function(req, res){
var name = (req.body.name != undefined)?req.body.name:req.query.name;
var city = (req.body.city != undefined)?req.body.city:req.query.city;
var state = (req.body.state != undefined)?req.body.state:req.query.state;
var place = new Place({
name: name,
city: city,
state: state
});
place.save(function(err){
if (err) throw err;
res.json({message: 'Created'});
});
});
var apiPlaces = require('./routes/api-places');
app.use('/api/places', apiPlaces);
// wire request controllers
var defaultController = require('./routes/defaultController');
defaultController.wire(app);
谢谢!