Node.js with Node-http-proxy to solve local development Ajax Cross-domain problems _node.js

Source: Internet
Author: User
Tags json require install node

Scene:

Before and after the separation, the local front-end development call interface will have cross-domain problems, there are generally the following 3 ways to solve:

1. Back-end interface package to run locally (disadvantage: Each back-end update to test the next update package, but also to build a local Java operating environment, trouble)

2. Cors cross-domain: Back-end interface in return, add ' Access-control-allow-origin ':* in header (sometimes the back end is not convenient to do this, the end of the egg pain)

3. Use Nodejs to build a local HTTP server, and to determine the interface URL when forwarding, the perfect solution for the local development of the cross-domain problem.

Technology to use:

1. Nodejs build Local HTTP Server

2. Apply Node-http-proxy, do the forwarding of interface URL

Specific methods:

1. Node.js build local HTTP Server reference Shawn.xie's "Nodejs build local HTTP Server"

2. Node.js do forwarding using NODE-HTTP-PROXY implementation, official documentation: HTTPS://GITHUB.COM/NODEJITSU/NODE-HTTP-PROXY#USING-HTTPS

3. The Operation method Reference: Http://hao.jser.com/archive/10394/?utm_source=tuicool&utm_medium=referral

4. Below is my own actual operation

Project preparation

1. NPM Initialization

NPM Init

2. Install Node-http-proxy module

NPM Install Http-proxy--save-dev

3. Project Structure


In the following example, we place the HTML file directly in the root directory './', or you can specify a site directory that can be customized in proxy.js

Configure HTTP server and proxy forwarding

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: ' http://192.168.10.38:8180/',//interface address//The following settings for HTTPS//SSL: {//Key:f
S.readfilesync (' Server_decrypt.key ', ' UTF8 '),//Cert:fs.readFileSync (' server.crt ', ' UTF8 ')//},//Secure:false});
Proxy.on (' Error ', function (err, req, res) {Res.writehead (+ {' 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 Realpa th = Path.join ("main-pages", pathname);
Specifies the root directory var realpath = Path.join ("./", pathname);
Console.log (pathname);
Console.log (Realpath);
var ext = path.extname (Realpath); Ext = ext?
Ext.slice (1): ' Unknown '; To determine if an interface is accessed, forward the IF (Pathname.ind) by proxyExof ("Mspj-mall-admin") > 0) {proxy.web (request, response); return;} fs.exists (Realpath, function (exists) {if (!exis  TS) {Response.writehead (404, {' Content-type ': ' Text/plain '}); Response.Write ("This request URL" + pathname + "is not
Found on this server. ");
Response.End (); else {fs.readfile (Realpath, "binary", function (err, file) {if (err) {response.writehead, {' Content-type ': ' Text
/plain '});
Response.End (ERR); else {var contentType = Mine[ext] | |
"Text/plain";
Response.writehead ({' Content-type ': ContentType});
Response.Write (File, "binary");
Response.End ();
}
});
}
});
});
Server.listen (PORT); Console.log ("Server runing at Port:" + Port + ".");

MINE. Js

Here reference Shawn.xie source code, supplemented a few font file 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 "
};

The above is the full source

Then change the interface address in the project to Http://localhost:3000/...

Start the Nodejs service

Start cmd, navigate to the project directory, run

Node Proxy.js

Access:

Http://localhost:3000/index.html

You can see the http://localhost:3000/called in the project .... will be from http://192.168.10.38:8180/... Gets the data, and then forwards it to the local.

This does not exist across domains.

The above is a small set to introduce node.js with Node-http-proxy to solve the local development of Ajax Cross-domain problem, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.