javascript - 使用 $http.post (angular) 和 bodyparser.text() 发送字符串请求时,请求正文作为对象返回?

标签 javascript angularjs http express post

当我发送一个字符串值作为请求时,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);
        }
    }

这是我在 Controller 中调用工厂的方式:

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 是一个字符串。

最佳答案

尝试“stringifyreq.body 以确定它是否仍作为 JSON 对象传递。您还可以尝试记录控制台,例如 console.log('this is req.body : ', req.body, ' --- ');

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

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

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

希望对您有所帮助;

关于javascript - 使用 $http.post (angular) 和 bodyparser.text() 发送字符串请求时,请求正文作为对象返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298702/

相关文章:

android - 管理 Android 应用程序 cookie

javascript - 如何在很长的运行循环javascript中更新innerHTML

Javascript - 原型(prototype)函数名称作为关联数组的键返回

javascript - 如果需要重要的变量和参数,如何使 Angular 应用程序安全?

javascript - 在带 Angular d3 折线图中用实际值绘制趋势线

Azure 逻辑应用 HTTP 请求条件不起作用

javascript - 如何忽略 phantomjs 中的错误

javascript - Google 如何检测搜索框中的输入以显示即时结果?

jquery - Angularjs Controller : how to call a controller in another controller?

c# - SoapHttpClientProtocol/HttpWebClientProtocol 连接状态