Node.js教程 如何解决本地开发时候的跨域问题
沉沙 2018-08-21 来源 : 阅读 2676 评论 0

摘要:本篇教程介绍了Node.js教程 如何解决本地开发时候的跨域问题,希望阅读本篇文章以后大家有所收获,帮助大家对Node.js的理解更加深入。

本篇教程介绍了Node.js教程 如何解决本地开发时候的跨域问题,希望阅读本篇文章以后大家有所收获,帮助大家对Node.js的理解更加深入。

<

 情景:
前后端分离,本地前端开发调用接口会有跨域问题,一般有以下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. 操作方法参考了://hao.jser.com/archive/10394/?utm_source=tuicool&utm_medium=referral
4. 下面是我自己的实战操作
项目准备
1. npm初始化

npm init

2. 安装node-http-proxy模块

npm install http-proxy --save-dev

3. 项目结构
 下面的例子中,我们把html文件直接放在根目录‘./‘,也可以指定一个网站目录,在proxy.js中可以自定义
 
配置HTTP服务器和PROXY转发

var PORT = 3000;

var http = require(‘http‘);
var url=require(‘url‘);
var fs=require(‘fs‘);
var mine=require(‘./mine‘).types;
var path=require(‘path‘);
var httpProxy = require(‘http-proxy‘);

var proxy = httpProxy.createProxyServer({
    target: ‘//192.168.10.38:8180/‘,   //接口地址
    // 下面的设置用于https
    // ssl: {
    //     key: fs.readFileSync(‘server_decrypt.key‘, ‘utf8‘),
    //     cert: fs.readFileSync(‘server.crt‘, ‘utf8‘)
    // },
    // secure: false
});

proxy.on(‘error‘, function(err, req, res){
    res.writeHead(500, {
        ‘content-type‘: ‘text/plain‘
    });
    console.log(err);
    res.end(‘Something went wrong. And we are reporting a custom error message.‘);
});

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    //var realPath = path.join("main-pages", pathname); // 指定根目录
    var realPath = path.join("./", pathname);
    console.log(pathname);
    console.log(realPath);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : ‘unknown‘;

    //判断如果是接口访问,则通过proxy转发
    if(pathname.indexOf("mspj-mall-admin") > 0){
        proxy.web(request, response);
        return;
    }

    fs.exists(realPath, function (exists) {
        if (!exists) {
            response.writeHead(404, {
                ‘Content-Type‘: ‘text/plain‘
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
            fs.readFile(realPath, "binary", function (err, file) {
                if (err) {
                    response.writeHead(500, {
                        ‘Content-Type‘: ‘text/plain‘
                    });
                    response.end(err);
                } else {
                    var contentType = mine[ext] || "text/plain";
                    response.writeHead(200, {
                        ‘Content-Type‘: contentType
                    });
                    response.write(file, "binary");
                    response.end();
                }
            });
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");

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

exports.types = {
  "css": "text/css",
  "gif": "image/gif",
  "html": "text/html",
  "ico": "image/x-icon",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "js": "text/javascript",
  "json": "application/json",
  "pdf": "application/pdf",
  "png": "image/png",
  "svg": "image/svg+xml",
  "swf": "application/x-shockwave-flash",
  "tiff": "image/tiff",
  "txt": "text/plain",
  "wav": "audio/x-wav",
  "wma": "audio/x-ms-wma",
  "wmv": "video/x-ms-wmv",
  "xml": "text/xml",
  "woff": "application/x-woff",
  "woff2": "application/x-woff2",
  "tff": "application/x-font-truetype",
  "otf": "application/x-font-opentype",
  "eot": "application/vnd.ms-fontobject"
};

以上就是全部源码
然后把项目中的接口地址改成//localhost:3000/......
 
启动nodejs服务
启动cmd,定位到项目目录,运行

node proxy.js

访问:

//localhost:3000/index.html

可以看到项目中调用的//localhost:3000/.....  都会从//192.168.10.38:8180/...... 获取数据,然后转发到本地。
这样就不存在跨域了。    

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注WEB前端Node.js频道!

本文由 @沉沙 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved