http proxy proxy

Cooperate with webpack and webpack-dev-server processing

  1. installation
// 安装 
cnpm html-webpack-plugin --save -D
cnpm install webpack webpack-cli webpack-dev-server --save -D
  1. New src folder New files index.html and index.js
  2. Send a request in index.js
import axios from 'axios'

axios.get('http://127.0.0.1:3001/user').then(result=>{
    console.log(result)
})
  1. New webpack.config.jsand configure
// 配置webpack.config.js
var path = require('path') // 绝对路径
const HtmlWebpackPlugin = require('html-webpack-plugin');// 打包html的插件

module.exports = {
    mode:'development', 
    // 入口文件
    entry: './src/index.js',
    // 出口文件
    output: {
        path:path.resolve(__dirname, 'build'), // 输出文件的存放路径
        filename: "bundle.js", //输出文件的名称
    },
    devServer:{
        port:3000,
        progress:true,
        contentBase:'./build',
    },
    plugins:[ // html产出插件的应用
        new HtmlWebpackPlugin({
            template:'./src/index.html',
            filename: 'index.html'
        })
    ]
}
  1. Create a new server.js service and write a user interface in it
let express = require('express')
let app = express()

app.get('/user',(req,res)=>{
      res.json({name:'jack'})
})
app.listen(3001,function(){
      console.log("server is running 3001")
})
  1. In package.jsonthe scriptsnext configuration
    "dev": "webpack-dev-server --open --host 127.0.0.1 --port 3000"
    so packed when completed will automatically open port 3000 window

  2. Start server.js service node server
    click the plus sign to open a new terminal drop-down box to switch terminal
    Insert picture description here

  3. Switching input terminal npm run devto package Packaging Success 3000 will automatically open the window
    Insert picture description here
    this time will see the console error
    Insert picture description here

solve…:

In the webpack.config.jsconfiguration proxyas follows

proxy:{ //代理过滤 处理跨域
      '/':{ 
          // 意思所有这个地址的请求都以 / 发送到 http://localhost:3001下
            target:'http://localhost:3001',
            changeOrigin:true // 改变源
      }
}

Insert picture description here
After repacking, you
npm run dev
will see some quick links to the data
Insert picture description here
:

Webpack packaging and configuration

JSONP and JQuery implement cross-domain

CORS cross-domain resource sharing

Published 41 original articles · Likes2 · Visits 1836

Guess you like

Origin blog.csdn.net/weixin_43883485/article/details/104784857