[英]Angular and Ajax Difference When Sending Request To NodeJS Server
我正在嘗試使用一些角度與NodeJS服務器進行通信。
我在JQuery中會做什么
$.ajax({
url: "/list",
type: "POST",
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log("data passed back from server is:" + data)
},
error: function(err) {
console.log("an error occured")
console.log(err)
}
})
我在用Angular做什么
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "/list"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
但是,使用angular時,瀏覽器會告訴我:
Failed to load resource: the server responded with a status of 404 (Not Found) localhost:3000/list
我沒有正確引用網址嗎?
服務器
app.post('/list', function (req, res){
// Establish connection to db
con.query('SELECT * FROM employees',function(err,rows){
if(err) throw err;
for (var i = 0; i < rows.length; i++) {
listArray.push(rows[i])
};
/*
ar names = listArray.map(function(item) {
return item;
});
console.log(names)
*/
res.send(listArray)
})
您的ajax調用似乎正在向/list
發出POST
請求,但是在Angular中,您已指定GET
現在,節點配置正在等待POST
請求。 您應該能夠簡單地將angular方法更改為POST
。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "POST",
url : "/list"
}).then(function mySucces(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.