【问题标题】:Error when requesting API from Angular and Nodejs从 Angular 和 Nodejs 请求 API 时出错
【发布时间】:2019-11-21 11:44:44
【问题描述】:

我正在尝试使用 Nodejs 服务器作为代理服务器来绕过特定 API 的 CORS,例如 darksky.net 或 googleapis。如下面的 Angular 8 代码所示,我尝试向我的 NodeJS 服务器发送一个获取请求,并传递三个参数。 NodeJs 服务器收到这些参数后,我请求 API,但得到 404 错误作为回报。

角度代码:

this.http.get('search/coords/', 
    {
      params: {
        address: this.street,
        city: this.city,
        state: this.state
      }
    }).subscribe(data => {
      this.lattitude = data['results']['geometry']['location']['lat'];
      this.longitude = data['results']['geometry']['location']['lon'];
      console.log(this.lattitude);
      console.log(this.longitude);
      this.coords = {
        lat: this.lattitude,
        lon: this.longitude
      };
    });
    return this.coords;
  }

这是我当前的 Nodejs/Express 代码:

const express = require('express')
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
var request = require('request');

const app = express();
var url = "";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'false'}));
app.use(cors());

app.get('search/coords/', function (req, res) {
    var street = req.query.address;
    var city = req.query.city;
    var state = req.query.state;
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + street + "," + city + "," + state + "&key=blah/"
    request(url, function(error, response, body) {
        if (!error && response.statusCode == 200) {
            var info = JSON.parse(body);
            res.send(info);
        }
    })
});

具体来说,我收到一个 GET 404 not found 错误和一个 ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/search/coords/?address......." 我是Angular 和 nodejs 的新手,因此非常感谢任何帮助。

【问题讨论】:

    标签: node.js ajax angular get request


    【解决方案1】:

    有两个问题:

    1. 首先是你没有启动Node服务器
    2. 其次,如果您调用this.http.get('search/coords', ...),则该请求的默认域是当前域,即http://localhost:4200,而不是您的节点服务器端口。

    要使其发挥作用,您需要解决以上两个问题。

    首先,将此代码添加到 Node.js 服务器文件(在最底部),使其监听某个端口:

    app.listen(3000, () => {
    
        console.log('Listening on port', 3000);
    });
    

    然后,修改您的 Angular 代码,使其看起来像这样:

    this.http.get('http://localhost:3000/search/coords/', ....);
    

    它应该这样工作。

    【讨论】:

    • 我合并了你的两个解决方案(在我原来的帖子中我忘记包含 app.listen 命令),但不幸的是我仍然收到“加载资源失败:服务器响应状态为 404 (未找到)”。这可能与我的角度配置文件有关吗?我在我的 node js 函数中添加了一个控制台日志,但它没有被调用,这让我相信 nodejs 获取路径没有收到我的角度 GET 请求。
    • 查看错误消息,它肯定根本没有命中 Node.js 服务器。您确定您的 Node.js 服务器已启动并且您已直接使用 Node.js 服务器 URL:this.http.get('http://localhost:3000/search/coords/', ....);?端口号是一个例子,根据你的设置调整
    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2021-01-07
    • 2020-04-21
    相关资源
    最近更新 更多