Use devServer to solve cross-domain problems

At present, the main solutions to cross-domain are:

jsonp (eliminated)
cors
http proxy
introduced here to use devServer to solve cross-domain, in fact, the principle is http proxy

Send all ajax requests to the devServer server, and then the devServer server will forward it once and send it to the data interface server

Since the ajax request is sent to the devServer server, there is no cross-domain, and because the devServer is an http request sent by the node platform, it naturally does not involve cross-domain problems, and can be perfectly solved!

Server code (just return a string):

const express = require('express')
const app = express()
// const cors = require('cors')
// app.use(cors())
app.get('/api/getUserInfo', (req, res) => {
  res.send({
    name: '黑马儿',
    age: 13
  })
});

app.listen(9999, () => {
  console.log('http://localhost:9999!');
});

The front end needs to configure the proxy function of devServer, and configure it in webpack.dev.js:

devServer: {
    open: true,
    hot: true,
    compress: true,
    port: 3000,
    // contentBase: './src'
    proxy: {
      '/api': 'http://localhost:9999'
    }
  },

When it means the front-end request / api url, webpack-dev-server will forward the request to http: // localhost: 9999 / api. At this time, if the request address is http: // localhost: 9999 / api / getUserInfo, only Need to write / api / getUserInfo directly, the code is as follows:

axios.get('/api/getUserInfo').then(result => console.log(result))

 

Guess you like

Origin www.cnblogs.com/wtsx-2019/p/12757595.html