Completely solve the cross-domain problem of front-end development in the process of front-end and back-end separation

Today's web projects are getting bigger and bigger, and the traditional development model has become stretched. Not only is it painful for developers during the development process, but it is also more painful for those who maintain it later. How to solve it? Front and rear separation. The problem that has always accompanied us in the front-end and back-end development process is the cross-domain problem, because at this time the front-end and back-end codes are running on different machines, and the two addresses are not under the same domain name. At this time, the front-end script is accessing ajax. When the browser will report cross-domain related errors. How to solve it at this time? 
The easiest way to do this is to allow browser cross-domain requests by setting the browser. But today we won't talk about this method here. If you are interested, you can search for the "Chrome browser cross-domain settings" tutorial on Du Niang. The tutorial is very detailed. This method is limited, because the cross-domain settings of different browsers are not the same, and even the settings of different versions of the same browser may be different. I only know the cross-domain settings of chrome, and I have seen them in IE and firefox. But I can't remember. In short, setting the browser to cross-domain is only suitable for temporary use. 
Next, we introduce a way to solve the cross-domain access of the front end by geodesy, and the way of forwarding the request of the local server. 
The process of implementation is to start a service locally on our front end, and then all ajax accesses on our front end prefer to access our local service. The local service will not process the incoming request, but only forward the request to our real background service. go up. Our local service is actually a transit point for you. This solution is that there is no cross-domain problem using access between backends. 
Now nodejs is in a mess, so it is quite simple for front-end personnel to build a local forwarding service. Next, we will use nodejs+express+http-proxy-middleware to build a forwarding service: 
1. Install nodejs 
2. Create a new project folder project 
3. Open the dos window in this folder and install express and http-proxy-middleware

npm install express http-proxy-middleware --save-dev

4. Create new server.js and public folders (used to store our front-end projects)

var express = require('express'); var proxyMiddleWare = require("http-proxy-middleware"); var proxyPath = "http://xxx.xx.xx.xx:port";//目标后端服务地址 var proxyOption ={target:proxyPath,changeOrigoin:falsevar app = express(); app.use(express.static("./public"))//这段程序的作用是将我们的前端项目设置成静态资源这样我们在浏览器中就可以直接通过http://127.0.0.1:xxxx/xxx(所在页面的目录层级)访问我们的页面,做到边开发边调试. app.use("/login",proxyMiddleWare(proxyOption))//这里要注意"/login" 是匹配的路由,它会将匹配的路由进行转发,没匹配到的就不会转发。 app.listen(8080);

5. Run server.js Open the dos window and run server.js in the directory where server.js is located. 
It's that simple. A simple front-end development environment with front-end and back-end separation that can be cross-domain is set up. We only need to set up our project. Just build it in the public folder. Then proxyPath is configured to the real backend service address we want to access. 
Now the popular front-end framework vue has actually implemented the request proxy in its webpack configuration file /build/dev-server.js:

require('./check-versions')() var config = require('../config'if (!process.env.NODE_ENV) { process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV) } var opn = require('opn'var path = require('path'var express = require('express'var webpack = require('webpack'var proxyMiddleware = require('http-proxy-middleware'var webpackConfig = require('./webpack.dev.conf'// default port where dev server listens for incoming traffic var port = process.env.PORT || config.dev.port// automatically open browser, if not set will be false var autoOpenBrowser = !!config.dev.autoOpenBrowser // Define HTTP proxies to your custom API backend // https://github.com/chimurai/http-proxy-middleware var proxyTable = config.dev.proxyTable var app = express() var compiler = webpack(webpackConfig) var devMiddleware = require('webpack-dev-middleware')(compiler, { publicPath: webpackConfig.output.publicPath, quiet: true }) var hotMiddleware = require('webpack-hot-middleware')(compiler, { log: () => {} }) // force page reload when html-webpack-plugin template changes compiler.plugin('compilation'function (compilation) { compilation.plugin('html-webpack-plugin-after-emit'function (data, cb) { hotMiddleware.publish({ action: 'reload' }) cb() }) })// proxy api requests Object.keys(proxyTable).forEach(function (context) { var options = proxyTable[context] if (typeof options === 'string') { options = { target: options } } app.use(proxyMiddleware(options.filter || context, options)) //代理请求 }) // handle fallback for HTML5 history APIapp.use(require('connect-history-api-fallback')()) // serve webpack bundle output app.use(devMiddleware) // enable hot-reload and state-preserving // compilation error display app.use(hotMiddleware) // serve pure static assets var staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory) app.use(staticPath, express.static('./static'))//这是静态资源 var uri = 'http://localhost:' + port devMiddleware.waitUntilValid(function () { console.log('> Listening at ' + uri + '\n') }) module.exports = app.listen(port, function (err) { if (err) { console.log(err) return } // when env is testing, don't need open it if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') { opn(uri) } })

In the front-end development of Vue, we actually started a static server locally after npm run dev. 
This way we can make cross-domain requests.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325621717&siteId=291194637