我正在尝试使用Nodejs服务器作为代理服务器来绕过特定API的CORS,例如darksky.net或googleapis。如下面的Angular 8代码所示,我尝试向NodeJS服务器发送get请求,传递三个参数。一旦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);
}
})
});具体地说,我收到一个Get404Not found错误和一个错误HttpErrorResponse {headers: HttpHeaders,status: 404,statusText:"Not Found",url:"http://localhost:4200/search/coords/?address.......“我是angular和nodejs的新手,因此任何帮助都将不胜感激。
发布于 2019-11-21 19:56:29
有两个问题:
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/', ....);应该是这样的。
https://stackoverflow.com/questions/58974227
复制相似问题