简体   繁体   English

Angular和NodeJS Express的RESTful获取请求

[英]RESTful Get Request with Angular & NodeJS Express

I'm just following tutorials and figuring out how to handle get requests in NodeJS. 我只是在跟随教程并弄清楚如何在NodeJS中处理获取请求。

Here are snippets of my code: 这是我的代码片段:

NodeJS: NodeJS:

router.get('/test', function(request, response, next) {
    console.log("Received Get Request");
    response.jsonp({
        data: 'test'
    });
});

Angular: 角度:

$http.get("http://localhost:3000/test").
success(function(response) {
    alert("OK");
}).
error(function(response) {
    alert("FAIL");
});

If I try to access the link directly @ localhost:3000/test , I'm able to receive the JSON message correctly. 如果我尝试直接通过localhost:3000/test访问链接,则可以正确接收JSON消息。 But when I use angularJS $http call, the request always fails and I'll find this error in the network inspector (Response) 但是,当我使用angularJS $ http调用时,请求总是失败,并且我会在网络检查器中找到此错误(响应)

SyntaxError:JSON.parse:unexpected end of data at line 1 column 1 of the JSON data SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束

The reason for that is because the response is empty but the response code is 200 in both cases. 这样做的原因是因为响应为空,但在两种情况下响应代码均为200。

I've tried searching for hours but maybe someone can enlighten me on this? 我尝试搜索几个小时,但是也许有人可以启发我吗?

you could try and send res.send('test') 您可以尝试发送res.send('test')

and then on your http request you can use 'then' 然后在您的http请求上,您可以使用'then'

$http.get("http://localhost:3000/test").then(function(res) {
      console.log(res);
})

unlike success, then will give you a complete object (with 'test' - string as res.data) 与成功不同的是,它将为您提供完整的对象(带有“ test”-字符串作为res.data)

success will bring you only the data; 成功只会为您带来数据;

then will bring you the whole object (with the status and such).. 然后将带给您整个对象(包括状态等)。

now about that jsonp .. it's used to override a json response. 现在关于该jsonp ..它用于覆盖json响应。 you could simply use 'res.json({data: 'test'})' and it should also work for you.. 您可以只使用'res.json({data:'test'}))',它也应该对您有用。

hope it helps 希望能帮助到你

You're using jsonp in node, which you probably don't need to. 您正在节点中使用jsonp,您可能不需要。 This adds extra characters to the response and so the JSON parser fails to parse (that's what the error is telling you, the JSON is malformed) 这会在响应中添加额外的字符,因此JSON解析器无法解析(这就是错误告诉您的信息,JSON格式错误)

Try changing the server to look like 尝试更改服务器外观

response.json({
    data: 'test'
});

If you look in the Network pane of the developer tools, you should be able to see the raw response. 如果查看开发人员工具的“网络”窗格,则应该能够看到原始响应。 It should look something like: 它看起来应该像这样:

{"data" : "test"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM