[英]Sending data from Angular to Express
I don't understand why I cannot get the data I POST form with Angular.js Express. 我不明白为什么我无法使用Angular.js Express获取POST表单中的数据。
Angular Part : 角部分:
$http.post(baseURL+"/search", data).success(function(data, status) {
$scope.results = data;
});
Express Part : 快递部分:
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/search', function(req, res){
console.log(req.query, req.body, req.params);
});
The log is {} {} {}. 日志为{} {} {}。 I can't figure out what am I doing wrong.
我不知道我在做什么错。
I also tried : 我也尝试过:
$http({
method: "POST",
url : baseURL+"/search",
data : {name: 'tete'},
headers: {'Content-Type': 'application/json'}
}).success( function(data){
console.log(data);
});
It doesn't work too. 它也不起作用。
Angular sends data as JSON by default. Angular默认以JSON格式发送数据。
$httpProvider.defaults.headers.post //Content-Type: application/json
You're only including the urlencoded
body-parser middleware. 您只包括使用
urlencoded
身体分析器中间件。 You need to include bodyParser.json()
. 您需要包括
bodyParser.json()
。
app.use(bodyParser.json());
app.post('/search', function(req, res){
console.log(req.body);
});
It seems that Angular $http
service sends data as JSON and you're missing appropriate bodyParser. 似乎Angular
$http
服务将数据作为JSON发送,并且您缺少适当的bodyParser。
Try replacing your bodyParser with app.use(bodyParser.json());
尝试将您的bodyParser替换为
app.use(bodyParser.json());
before your POST route in Express. 在Express中的POST路线之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.