不用20行搞定node反向代理

proxy.js

var express = require('express');

var app = express();

var proxy = require('http-proxy-middleware');

var host = 'localhost';

var port = '3000';

app.use('/',express.static('static'));//设置静态资源

app.use('/api/*',proxy({

    target:'http://music.163.com/api',//代理域名或ip

    changeOrigin:true,

    pathRewrite:{

        '^/api':''

    }

}))

app.listen(port,function () {

    console.log("server is listening at http://%s:%s",host,port)

})

跟目录下创建static文件夹,此文件夹为静态资源目录。在static目录下创建index.html。

index.html 内正常使用ajax,url地址更换为proxy.js中的需要被转发的路径。

此示例为, '/api/playlist/detail?id=19723756''

不使用代理情况下,资源请求存在跨域问题

Failed to load http://music.163.com/api/playlist/detail?id=19723756: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

在使用代理后,则能正常请求到所需信息,不过前提是被请求的服务端没有做过多严格的限制。

node 通过反向代理获取的数据

记得启动服务哦!

node proxy.js

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容