Jquery Nodejs和expressjs。Ajax get请求不返回数据
我在JS中有以下Api:Jquery Nodejs和expressjs。Ajax get请求不返回数据,jquery,node.js,express,asp.net-web-api,nodeapi,Jquery,Node.js,Express,Asp.net Web Api,Nodeapi,我在JS中有以下Api: router.route('/books') .get(function(req,res){ Repository.getAll().done( function(result){ res.json(result);},function(err){res.send(err);}); }) .post(function(req,res){ Repository.save(req.body).done( func
router.route('/books')
.get(function(req,res){
Repository.getAll().done( function(result){ res.json(result);},function(err){res.send(err);});
})
.post(function(req,res){
Repository.save(req.body).done( function(object){ res.json(object); },function(err){res.send("error seems to have occured");});
});
当我使用Fiddler发布和使用chrome浏览器获取时,它工作得很好。但当我尝试使用jquery获取和发布时:
$.ajax({
type: "POST",
url: "http://localhost:8000/api/books",
data: { "title":"My name is","releaseYear":"1989","director":"me","genre":"horror" }
}).done(function(data) {
//alert("Success.");
console.log("success");
}).error(function(data, err, e, o) {
console.log("error");
//alert("Sorry. Server unavailable. ");
});
$.ajax({
type: "GET",
url: "http://localhost:8000/api/books",
contentType: "application/json"
}).done(function(data) {
//alert("Success.");
console.log("success");
}).error(function(data, err, e, o) {
console.log("error");
//alert("Sorry. Server unavailable. ");
});
启动失败/错误回调。我尝试指定contentType或删除它,但没有效果
调用POST时,状态代码为200,但没有返回任何数据,调用失败函数您是否尝试添加
数据类型:“json”
?在发布之前,您还应该尝试在对象上运行JSON.stringify()
。您的请求正在调用“/api/books”,而您只在侦听“/books”
将客户端代码请求url修改为:
$.ajax({
type: "POST",
url: "http://localhost:8000/books",
data: { "title":"My name is","releaseYear":"1989","director":"me","genre":"horror" }
}).done(function(data) {
//alert("Success.");
console.log("success");
}).error(function(data, err, e, o) {
console.log("error");
//alert("Sorry. Server unavailable. ");
});
$.ajax({
type: "GET",
url: "http://localhost:8000/books",
contentType: "application/json"
}).done(function(data) {
//alert("Success.");
console.log("success");
}).error(function(data, err, e, o) {
console.log("error");
//alert("Sorry. Server unavailable. ");
});
或者将服务器代码修改为:
router.route('/api/books')
.get(function(req,res){
Repository.getAll().done( function(result){ res.json(result);},function(err){res.send(err);});
})
.post(function(req,res){
Repository.save(req.body).done( function(object){ res.json(object); },function(err){res.send("error seems to have occured");});
});
您的请求正在调用“/api/books”,而您只在侦听“/books”您是否调试了客户端和服务器结果以确保其包含任何数据?İlker Korkut:调试服务器将是一项任务,因为我以前从未调试过节点。娜达:事实并非如此。我打电话的网址是correct@user1809104安装节点检查器以调试应用程序。这里可能是他正在使用前缀路由器
app.use('/api',router)代码>?所以最好在他的问题中指定:d要调用的正确url是:。我使用带前缀的路由器。如前所述,这似乎适用于其他任何地方,但当使用jquery@user1809104执行console.log(json(result))
或console.log(json(object))查看服务器上的结果是否为空。从ajax URL中删除“”。检查CORs或类似的控制台错误。只要检查请求是否到达服务器,服务器响应是什么(在服务器端)Nada:使用http.get(“”,function(http_res){}我可以从服务器端调用它得到结果。我也可以从chrome发出请求,没有问题。返回的错误简单地说是“error”在失败回调中。不需要console.log任何东西,因为它在其他地方工作