Angular:$ http请求给出-1状态

tm1*_*701 5 angularjs angularjs-http

node.js服务器给出"这是一个字符串".(writeHeader,write(string),end).

执行$ http请求时,我看到node.js服务器正在响应并发回信息.

在Angular中,我执行以下请求:

angular.module('phoneList').
  component('phoneList', {
  templateUrl: 'phone-list/phone-list.template.html',
  controller: function PhoneListController($http) {
    var self = this;
    $http.get('http://127.0.0.1:8081/echo').then(function(response) {
      self.data = response.data;
    }, function(err) {
      self.error = err;
      self.status = response.status;
      self.statusText = response.statusText;
  }); 
 }
});
Run Code Online (Sandbox Code Playgroud)

响应

{"data":null,"status": - 1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":" http: //127.0.0.1:8081/echo ","headers":{"接受":"application/json,text/plain,/ "}},"statusText":""}

我试过从node.js或HTML-text发送JSON.没有不同.

Seb*_*ald 5

请查阅官方 Angular 文档以了解 $http。它声明如下:

此外,小于 -1 的状态代码被归一化为零。-1 通常意味着请求被中止,例如使用 config.timeout。

所以我想这是你的后端的问题。也许查看开发者控制台以检查请求是否到达您的服务器。


tm1*_*701 5

非常感谢@Sebastian Sebald@Dex指导我找到解决方案.我只是想在我的计算机上运行一个简单的Node.js服务器,向我的(简单)Angular脚本提供消息.

是的,这是一个跨域问题. @TonyTakeshi为这个问题提供了一个很好的解决方案.您可以通过以下方式在node.js服务器文件中解决它:

app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});
Run Code Online (Sandbox Code Playgroud)

重量级的简单测试配置;-)