当前位置:Gxlcms > JavaScript > Node.js配合node-http-proxy解决本地开发ajax跨域问题

Node.js配合node-http-proxy解决本地开发ajax跨域问题

时间:2021-07-01 10:21:17 帮助过:7人阅读

情景:

前后端分离,本地前端开发调用接口会有跨域问题,一般有以下3种解决方法:

1. 后端接口打包到本地运行(缺点:每次后端更新都要去测试服下一个更新包,还要在本地搭建java运行环境,麻烦)

2. CORS跨域:后端接口在返回的时候,在header中加入'Access-Control-Allow-origin':* 之类的(有的时候后端不方便这样处理,前端就蛋疼了)

3. 用nodejs搭建本地http服务器,并且判断访问接口URL时进行转发,完美解决本地开发时候的跨域问题。

 用到的技术:

1. nodejs搭建本地http服务器

2. 应用node-http-proxy,做接口url的转发

具体方法:

1. node.js搭建本地http服务器参考了shawn.xie的《nodejs搭建本地http服务器》

2. node.js做转发使用node-http-proxy实现,官方文档:https://github.com/nodejitsu/node-http-proxy#using-https

3. 操作方法参考了:http://hao.jser.com/archive/10394/?utm_source=tuicool&utm_medium=referral

4. 下面是我自己的实战操作

项目准备

1. npm初始化

  1. npm init

2. 安装node-http-proxy模块

  1. npm install http-proxy --save-dev

3. 项目结构


下面的例子中,我们把html文件直接放在根目录'./',也可以指定一个网站目录,在proxy.js中可以自定义

配置HTTP服务器和PROXY转发

  1. var PORT = 3000;
  2. var http = require('http');
  3. var url=require('url');
  4. var fs=require('fs');
  5. var mine=require('./mine').types;
  6. var path=require('path');
  7. var httpProxy = require('http-proxy');
  8. var proxy = httpProxy.createProxyServer({
  9. target: 'http://192.168.10.38:8180/', //接口地址
  10. // 下面的设置用于https
  11. // ssl: {
  12. // key: fs.readFileSync('server_decrypt.key', 'utf8'),
  13. // cert: fs.readFileSync('server.crt', 'utf8')
  14. // },
  15. // secure: false
  16. });
  17. proxy.on('error', function(err, req, res){
  18. res.writeHead(500, {
  19. 'content-type': 'text/plain'
  20. });
  21. console.log(err);
  22. res.end('Something went wrong. And we are reporting a custom error message.');
  23. });
  24. var server = http.createServer(function (request, response) {
  25. var pathname = url.parse(request.url).pathname;
  26. //var realPath = path.join("main-pages", pathname); // 指定根目录
  27. var realPath = path.join("./", pathname);
  28. console.log(pathname);
  29. console.log(realPath);
  30. var ext = path.extname(realPath);
  31. ext = ext ? ext.slice(1) : 'unknown';
  32. //判断如果是接口访问,则通过proxy转发
  33. if(pathname.indexOf("mspj-mall-admin") > 0){
  34. proxy.web(request, response);
  35. return;
  36. }
  37. fs.exists(realPath, function (exists) {
  38. if (!exists) {
  39. response.writeHead(404, {
  40. 'Content-Type': 'text/plain'
  41. });
  42. response.write("This request URL " + pathname + " was not found on this server.");
  43. response.end();
  44. } else {
  45. fs.readFile(realPath, "binary", function (err, file) {
  46. if (err) {
  47. response.writeHead(500, {
  48. 'Content-Type': 'text/plain'
  49. });
  50. response.end(err);
  51. } else {
  52. var contentType = mine[ext] || "text/plain";
  53. response.writeHead(200, {
  54. 'Content-Type': contentType
  55. });
  56. response.write(file, "binary");
  57. response.end();
  58. }
  59. });
  60. }
  61. });
  62. });
  63. server.listen(PORT);
  64. console.log("Server runing at port: " + PORT + ".");

MINE.JS

这里参考shawn.xie的源码,补充了几个字体文件的mime。

  1. exports.types = {
  2. "css": "text/css",
  3. "gif": "image/gif",
  4. "html": "text/html",
  5. "ico": "image/x-icon",
  6. "jpeg": "image/jpeg",
  7. "jpg": "image/jpeg",
  8. "js": "text/javascript",
  9. "json": "application/json",
  10. "pdf": "application/pdf",
  11. "png": "image/png",
  12. "svg": "image/svg+xml",
  13. "swf": "application/x-shockwave-flash",
  14. "tiff": "image/tiff",
  15. "txt": "text/plain",
  16. "wav": "audio/x-wav",
  17. "wma": "audio/x-ms-wma",
  18. "wmv": "video/x-ms-wmv",
  19. "xml": "text/xml",
  20. "woff": "application/x-woff",
  21. "woff2": "application/x-woff2",
  22. "tff": "application/x-font-truetype",
  23. "otf": "application/x-font-opentype",
  24. "eot": "application/vnd.ms-fontobject"
  25. };

以上就是全部源码

然后把项目中的接口地址改成http://localhost:3000/......

启动nodejs服务

启动cmd,定位到项目目录,运行

  1. node proxy.js

访问:

http://localhost:3000/index.html

可以看到项目中调用的http://localhost:3000/..... 都会从http://192.168.10.38:8180/...... 获取数据,然后转发到本地。

这样就不存在跨域了。

以上所述是小编给大家介绍的Node.js配合node-http-proxy解决本地开发ajax跨域问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

人气教程排行