四、使用代理解决跨域问题

一、在src下新建setupProxy.js文件

不要乱起名字,一定要是这个文件名

  • 安装http-proxy-middleware插件
    yarn add http-proxy-middleware
//setupProxy.js
const {
  createProxyMiddleware
} = require('http-proxy-middleware')
module.exports = function (app) {
  app.use('/api1',
    createProxyMiddleware({
      target: 'http://localhost:3001', //配置转发目标地址
      changeOrigin: true, //控制服务器接收到的请求头中host字段的值
      pathRewrite: {
        '^/api1': ''
      } //去除请求前缀址(必须配置)
    }),
  ),
  app.use('/api2',
    createProxyMiddleware({
      target: 'http://localhost:3002', 
      changeOrigin: true, 
      pathRewrite: {
        '^/api2': ''
      }
    }),
  )
}

二、跨域演示

//app.js
import { useState } from "react";
import { http } from './utils/http';

function App() {
  // 声明一个新的叫做 “count” 的 state 变量
  const [count, setCount] = useState(0);

  const add = async (res) => {
    setCount(count + res)
  }

  const getData1 = async () => {
    let getData = await http.get('/api1/stu')
    console.log(getData.data);
  }

  const getData2 = async () => {
    let getData = await http.get('/api2/stu')
    console.log(getData.data);
  }


  return (
    <div className="App">
      <p>You clicked {count} times</p>
      <button onClick={ () => add(1)}>
        Click me
      </button>
      <hr />
      <button onClick={ () => getData1()}>3001端口请求数据
      </button><button onClick={ () => getData2()}>3002端口请求数据
      </button>
    </div>
  );
}


export default App;
//http.js

import axios from 'axios'

const http = axios.create({})


export {
  http
}

三、服务端代码

//app.js
const express = require('express')

const app = express()

app.get('/stu', ( req, res ) => {
  res.send('3001端口请求回来的数据')
  res.end()
})

app.listen(3001, () => {
  console.log('3001端口服务启动成功');
})
//server.js
const express = require('express')

const app = express()

app.get('/stu', ( req, res ) => {
  res.send('3002端口请求回来的数据')
  res.end()
})

app.listen(3002, () => {
  console.log('3002端口服务启动成功');
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值