NodeJS 代理请求 Google & Yelp

标签: NodeJS API node-fetch
12人阅读 评论(0) 收藏 举报
分类:

项目简介:

NodeJS 作为服务器,接收前端请求,经过处理转发对应 Yelp 与 Google API ,返回请求结果。通过此种方式,可避免暴露 API Key,并可在服务器端可翻情况下突破访问限制。另外,项目使用 Node-Fetch,使用简单,便于理解。

目录结构:

|- - - - GoogleYelpTest
|- - - - - - - node_modules
|- - - - - - - server.js
|- - - - - - - package.json
|
|- - - - Client
|- - - - - - - index.html

执行步骤:

npm init
npm install node-fetch --save
npm install express --save
node ./server.js

代码文件:

package.json

{
  "name": "googleyelpapi",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node ./server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "node-fetch": "^2.1.2"
  }
}

server.js

var fetch = require('node-fetch');
var express = require('express');
var fs = require('fs');

var app = express();

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", '3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


//  备注:
//     以下请求均为 GET 请求
//     请求中的 API Key 出于隐私考虑,使用 [Your Key] 代替
//     每个方法前均两句用例注释,上句为前端请求内容,下句为 NodeJS 请求相应 API 内容


//  "Best Matches"
//  localhost:8081/yelp/best_match?name=Gary Danko&city=San Francisco&state=CA&country=US&address1=800 N Point St
//  https://api.yelp.com/v3/businesses/matches/best?name=Gary Danko&city=San Francisco&state=CA&country=US&address1=800 N Point St
app.get('/yelp/best_match', function(req, res) {
    const query = req.query;
    let result = {};

    fetch(`https://api.yelp.com/v3/businesses/matches/best?name=${query.name}&city=${query.city}&state=${query.state}&country=${query.country}&address1=${query.address1}`, {
            headers: {
                'Authorization': 'Bearer [Your Key]'
            }
        })
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" YELP BEST MATCH ");
})


//  "Yelp Reviews"
//  localhost:8081/yelp/WavvLdfdP6g8aZTtbBQHTw/reviews
//  https://api.yelp.com/v3/businesses/WavvLdfdP6g8aZTtbBQHTw/reviews
app.get('/yelp/:key/reviews/', function(req, res) {
    const query = req.query;

    fetch(`https://api.yelp.com/v3/businesses/${req.params.key}/reviews`, {
            headers: {
                'Authorization': 'Bearer [Your Key]'
            }
        })
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" YELP REVIEWS ");
})

//  "Google Nearby"
//   http://localhost:8081/google/nearby?latGeo=-33.8670522&lonGeo=151.1957362&radius=1000&types=food&keyword=vegetarian&key=[Your Key]
//   https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1000&types=food&keyword=vegetarian&key=[Your Key]
app.get('/google/nearby', function(req, res) {
    const query = req.query;
    let distance = (distance | 10) / (0.000621);

    fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${query.latGeo},${query.lonGeo}&radius=${distance}&types=${query.types}&keyword=${query.keyword}&key=[Your Key]`)
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" Google Nearby ");
})

//  "Google Nearby Next"
//  http://localhost:8081/google/nearby/next?pagetoken=CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q&key=[Your Key]
//  https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=CpQCAgEAAFxg8o-eU7_uKn7Yqjana-HQIx1hr5BrT4zBaEko29ANsXtp9mrqN0yrKWhf-y2PUpHRLQb1GT-mtxNcXou8TwkXhi1Jbk-ReY7oulyuvKSQrw1lgJElggGlo0d6indiH1U-tDwquw4tU_UXoQ_sj8OBo8XBUuWjuuFShqmLMP-0W59Vr6CaXdLrF8M3wFR4dUUhSf5UC4QCLaOMVP92lyh0OdtF_m_9Dt7lz-Wniod9zDrHeDsz_by570K3jL1VuDKTl_U1cJ0mzz_zDHGfOUf7VU1kVIs1WnM9SGvnm8YZURLTtMLMWx8-doGUE56Af_VfKjGDYW361OOIj9GmkyCFtaoCmTMIr5kgyeUSnB-IEhDlzujVrV6O9Mt7N4DagR6RGhT3g1viYLS4kO5YindU6dm3GIof1Q&key=[Your Key]
app.get('/google/nearby/next', function(req, res) {
    const query = req.query;
    console.log(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=${query.pagetoken}&key=[Your Key]`);
    fetch(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=${query.pagetoken}&key=[Your Key]`)
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" Google Nearby Next ");
})

//  "Google Place"
//  http://localhost:8081/google/details?placeid=ChIJN1t_tDeuEmsRLIWYxBbGKeA&key=[Your Key]
//  https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRLIWYxBbGKeA&key=[Your Key]
app.get('/google/details', function(req, res) {
    const query = req.query;
    let result = {};

    fetch(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${query.placeid}&key=[Your Key]`)
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" Google Details ");
})

//  "Google Place"
//   localhost:8081/google/geocode?address=US&key=[Your Key]
//   https://maps.googleapis.com/maps/api/geocode/json?address=US&key=[Your Key]
app.get('/google/geocode', function(req, res) {
    const query = req.query;

    fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${query.address}&key=[Your Key]`)
        .then(res => res.json())
        .then(json => res.send(json));

    console.log(" Google Geocode ");
})

//  "Google Place"
//   localhost:8081/google/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=[Your Key]
//   https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=CnRtAAAATLZNl354RwP_9UKbQ_5Psy40texXePv4oAlgP4qNEkdIrkyse7rPXYGd9D_Uj1rVsQdWT4oRz4QrYAJNpFX7rzqqMlZw2h2E2y5IKMUZ7ouD_SlcHxYq1yL4KbKUv3qtWgTK0A6QbGh87GB3sscrHRIQiG2RrmU_jF4tENr9wGS_YxoUSSDrYjWmrNfeEHSGSc3FyhNLlBU&key=[Your Key]
app.get('/google/photo', function(req, res) {
    const query = req.query;

    fetch(`https://maps.googleapis.com/maps/api/place/photo?maxwidth=1000&photoreference=${query.photoreference}&key=[Your Key]`)
        .then(res => {
            const dest = fs.createWriteStream(`./image1.png`, {
                autoClose: true,
            });
            res.body.pipe(dest);
        });

    console.log(" Google Photo ");
})

var server = app.listen(8081, function() {
    var host = server.address().address
    var port = server.address().port

    console.log(" 服务器配置: http://%s:%s", host, port)
})

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>NodeJs 服务器代理</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                // 此处访问 NodeJS 服务器,参数中无需带有 API Key
                $.get("http://localhost:8081/yelp/best_match?name=Gary Danko&city=San Francisco&state=CA&country=US&address1=800 N Point St", function(data, status) {
                    $("#status").html("Status: \n" + status);
                    $("#response").html(JSON.stringify(data));
                });
            });
        });
    </script>
</head>

<body>
    <div>
        <p>发送 HTTP GET 请求, 经由服务器处理并访问第三方 API, 返回结果</p>
        <button>按 钮</button>
        <div>
            <p id="status"></p>
            <p id="response"></p>
        </div>
    </div>
</body>

</html>

注意事项:

Yelp,美国最大在线点评网站,国内可访问
Google Place API,顾名思义,你懂得

查看评论

yelp_academic_dataset_tip.json

  • 2014年03月17日 23:35
  • 20.96MB
  • 下载

用node-http-proxy搭建谷歌代理

程序员三大必备网站是:Google、Github、StackOverflow。如果你还在用Baidu搜索技术文章的话,我想说的是,少年你已经被鄙视很多年了,赶紧换成谷歌吧,不要再被鄙视了!Github...
  • Jaye100
  • Jaye100
  • 2015-11-29 21:28:47
  • 9165

Nodejs https reqest by proxy(node通过代理进行https请求)

Code https_by_proxy.js var Http = require('http'); var Tls = require('tls'); var req = Http.reque...
  • tina_tian1
  • tina_tian1
  • 2016-12-20 17:52:20
  • 1508

用nodejs做代理访问外部接口系统,如何实现带参数的post请求?

var opt = {      host:'localhost',      port:'8888',      method:'POST',      path:'/getTicket',...
  • sjzwenzi
  • sjzwenzi
  • 2016-10-24 11:39:40
  • 1649

用 nodejs 做反向代理服务器

时下不少场景,都是申请一个 VPS 主机来托管运行 Web 项目的,小弟我也不例外——购买了一个小型的 CentOS VPS 使用着。在使用的过程中,面临一个问题,就是同一类型的服务端环境还好——但如...
  • zhangxin09
  • zhangxin09
  • 2014-07-15 21:41:32
  • 28461

nodejs request设置proxy

request.post({url:url,proxy:'http://username:pwd@url:port',oauth:oauth}  var options = {         hos...
  • yuan882696yan
  • yuan882696yan
  • 2014-05-05 15:17:16
  • 6020

使用Nodejs 的http-proxy 模块做代理服务器的尝试

我今天突然想到一个问题,如果使用nginx 作为nodejs 的代理服务器,那么如果nodejs的应用需要进行升级的话,如何实现热更新。   第一种办法:使用nodejs搭建一个代理服务器,通过对请...
  • zhihuoqian9683
  • zhihuoqian9683
  • 2018-01-01 06:36:44
  • 534

Node.js如何使用代理发送request请求?

 Node.js如何使用代理发送request请求?                        请问Node.js如何支持代理方式发送请求? 目前想支持的方式有 ht...
  • lisaem
  • lisaem
  • 2015-04-10 22:39:58
  • 752

nodejs中request模块proxy的使用方法

request.post({url:url,proxy:'http://username:password@url:port',oauth:oauth}  var options = {   ...
  • davidsu33
  • davidsu33
  • 2016-09-27 09:45:46
  • 2517

NodeJS实现HTTP/HTTPS代理

身在天朝,难免会用到代理的时候。 比如在学校内网用代理免费上外网,在墙内用代理上404网站等。     现在使用的代理大部分为HTTP和Socket代理。 Socket代理更底层,需要本地解...
  • qq_16619037
  • qq_16619037
  • 2016-03-28 11:22:46
  • 391
    个人资料
    等级:
    访问量: 5130
    积分: 112
    排名: 122万+
    文章存档
    最新评论