0

我有一个 angular2 应用程序,它使用 jwt 身份验证连接到 express/node 服务器。

我正在使用 angular2-jwt,这是我在 app.module.ts 中的配置

export function getAuthHttp(http) {
  return new AuthHttp(new AuthConfig({
    globalHeaders: [{'Accept': 'application/json'}],
    tokenName: 'my_token',
    tokenGetter: (() => localStorage.getItem('my_token')),
  }), http);
}

然后,对于我的 http 调用,我像这样使用它

getQuestions(): Observable<any> {
  return this.authHttp
    .get(`${this.settings.api}/questions`)
    .map((response: Response) => response.json());
}

其中 this.settings.api 是经过身份验证的 url。

问题是,这在我以前的 php 服务器上运行良好。我刚刚更改了 url 以在 Node 中使用我的新服务器,现在调用失败了,因为令牌未添加到标头中。

当我使用 chrome 控制台检查请求的标头时,我看到:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en,es-ES;q=0.8,es;q=0.6
Access-Control-Request-Headers:authorization
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:3050
Origin:http://evil.com/
Pragma:no-cache
Referer:http://localhost:8100/
User-Agent:...

如果我没记错的话,里面应该有一个Authorization: Bearer token,但它不见了。

我检查了在获取 AuthHttp 时是否可以检索令牌并且它正在工作,因此令牌存在并且可以访问。

有任何想法吗?谢谢,

编辑 我开始认为这可能与 CORS 有关,因为我的旧 php 服务器在另一台机器上,而新节点在我自己的机器上。会是这样吗?在这种情况下如何解决?

4

1 回答 1

0

所以,万一有人来了,我使用 Express 库解决了这个问题。

https://www.npmjs.com/package/cors

易于使用,只需app.use(cors());在我的节点服务器中的任何中间件之前添加。

于 2017-02-13T12:23:17.130 回答