Узлы и экспрессы. Ajax получает запрос не возвращая данные
У меня есть следующие Api в JS:
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. ");
});
Fail / error callback срабатывает. Я пытался указать contentType или удалить его, но безрезультатно.
При вызове POST код состояния равен 200, но данные не возвращаются и вызывает функцию сбоя
2 ответа
Ваш запрос звонит "/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");});
});
Вы пытались добавить dataType: "json"
? Вы также должны попробовать запустить JSON.stringify()
на вашем объекте перед публикацией.