2015-08-03 87 views
2

我不明白为什么我无法使用Angular.js Express获取我POST形式的数据。将数据从Angular发送到Express

角部位:

$http.post(baseURL+"/search", data).success(function(data, status) { 
     $scope.results = data; 
    }); 

快递部分:

app.use(bodyParser.urlencoded({ extended: false })); 
app.post('/search', function(req, res){ 
    console.log(req.query, req.body, req.params); 
}); 

日志是{} {} {}。 我无法弄清楚我做错了什么。

我也试过:

$http({ 
    method: "POST", 
    url : baseURL+"/search", 
    data : {name: 'tete'}, 
    headers: {'Content-Type': 'application/json'} 
}).success(function(data){ 
    console.log(data); 
}); 

它没有工作过。

回答

4

Angular默认发送数据为JSON。

$httpProvider.defaults.headers.post //Content-Type: application/json 

您只包含urlencoded body-parser中间件。您需要包含bodyParser.json()

app.use(bodyParser.json()); 
app.post('/search', function(req, res){ 
    console.log(req.body); 
}); 
1

似乎角$http服务发送数据作为JSON和你缺少适当bodyParser。

尝试使用Express在POST路线之前替换您的bodyParser并使用app.use(bodyParser.json());

+0

谢谢!它终于有效! – Prox