【问题标题】:Connection refused when accessing Node.js API from Angular从 Angular 访问 Node.js API 时连接被拒绝
【发布时间】:2020-06-26 03:25:09
【问题描述】:

我是 Angular 新手,我正在尝试在我的 Angular 网页中实现用户身份验证。作为后端,我使用 Node.js Express 框架和身份验证,我使用护照。

当我从浏览器访问服务器 URL 时,它可以正常工作,但是当我从 Angular 使用相同的 URL 调用 API 时,出现连接被拒绝错误 404。

[错误] 加载资源失败:服务器响应状态为 404(未找到)(用户,第 0 行)

这是我在浏览器中有效的 URL,但在 Angular 中无效(我使用 https): https://192.168.1.103:8000/users

这就是我的 Angular API 的样子:

get_user() {
    return this.http.post(environment.apiUrl + 'users', {
      observe: 'body',
      withCredentials: true,
      headers: new HttpHeaders().append('Content-Type', 'application/json')
    });
  }

我在 Node 服务器上的 API 如下所示:

router.get('/users', isValidUser, function (req, res, next) {
  return res.status(200).json(req.user)
});

function isValidUser (req, res, next) {
  if(req.isAuthenticated()) next ();
  else
    return res.status(401).json({message: 'Unauthorized request'});

}

浏览器控制台的输出如下所示:

[Error] ERROR
HttpErrorResponse

error: "<!DOCTYPE html><html><head><title></title><link rel=\"stylesheet\" href=\"/stylesheets/style.css\"></head><body><h1>No…"

headers: HttpHeaders {normalizedNames: Map, lazyUpdate: null, lazyInit: function}

message: "Http failure response for https://192.168.1.103:8000/users: 404 Not Found"

name: "HttpErrorResponse"

ok: false

status: 404

statusText: "Not Found"

url: "https://192.168.1.103:8000/users"

Prototyp HttpErrorResponse
    defaultErrorLogger (vendor.js:43427)
    handleError (vendor.js:43479)
    next (vendor.js:74051)
    (anonymná funkcia) (vendor.js:69627)
    __tryOrUnsub (vendor.js:115680)
    next (vendor.js:115619)
    _next (vendor.js:115567)
    next (vendor.js:115544)
    next (vendor.js:115330)
    emit (vendor.js:69589)
    run (polyfills.js:3359)
    onHandleError (vendor.js:73335)
    runTask (polyfills.js:3406)
    invokeTask (polyfills.js:3700)
    timer (polyfills.js:5885)

【问题讨论】:

  • environment.apiUrl 中保存了什么?
  • 这是来自文件 enviroment.ts 的我的 IP 地址
  • 你能控制台输出并粘贴到这里吗
  • 我更新了问题,你可以在那里找到它

标签: node.js angular api https passport.js


【解决方案1】:

您在 Angular 代码中使用的是发布请求而不是获取请求。我假设您没有在 nodejs 中定义 /users 的发布路线,因此出现错误

试试

get_user() {
return this.http.post(environment.apiUrl + 'users', {
  observe: 'body',
  withCredentials: true
});

}

此外,您不需要设置 Content-Type 标头,因为它是由 Angular HttpClient 自动设置的

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 2015-01-23
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2015-04-26
    • 2021-06-05
    • 2015-06-21
    • 1970-01-01
    相关资源
    最近更新 更多