【问题标题】:Body of request comes back as object when sending string request using $http.post (angular) and bodyparser.text()?使用 $http.post (angular) 和 bodyparser.text() 发送字符串请求时,请求正文作为对象返回?
【发布时间】:2017-03-10 23:16:28
【问题描述】:

当我发送一个字符串值作为请求时,req.body 值是一个对象。我正在使用:

我有一个工厂 cust1_service.postQuery:

.factory('cust1_service', function($http){
    return {
        postQuery : function(request){
            console.log('cust1 req : ' + request);
            console.log('typeof request : ' + typeof request);
            var config = {'Content-Type' : 'text/plain'};
            return $http.post('/cust1', request);
        }
    }

这是我在控制器中调用工厂的方式:

cust1_service.postQuery(req_string).success(handleSuccess);

我还在路由之前使用 bodyParser.text()

var express = require('express'),   
config = require('./config/config'),    
bodyParser = require('body-parser'),    
api = require('./app/routes/api.js');               

var app = express();

app.use(bodyParser.text({   
    type: "text/*"               
}));                             

app.use(express.static(__dirname + '/public'));     //Serve static assets

require('./app/routes/api.js')(app, db);

app.listen(config.port, function() {    
    console.log('Listening on ' + config.port); 
})

所以....当我到达我的路由 api 时

app.route('/cust1')
    .post(function(req,res){
            console.log('this is req.body : ' + req.body);

req.body 是 [object Object]...我是否将请求作为文本类型错误地发送?我需要 req.body 是一个字符串。

【问题讨论】:

    标签: javascript angularjs http express post


    【解决方案1】:

    尝试“stringifyreq.body 以确保它是否仍作为 JSON 对象传递。你也可以尝试像console.log('this is req.body : ', req.body, ' --- ');这样的控制台记录

    您可以尝试的一个解决方案是完全删除 BodyParser 中间件的使用 - 这应该强制正文为文本。 所以你需要删除或注释掉这一行:

    app.use(bodyParser.text({ type: "text/*"})) 
    

    你可以看一个密切相关的问题here.

    我希望这会有所帮助;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多