(1): 在package.json下新建proxy的(第一种方式)
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8888",
(2): 下载中间件 http-proxy-middleware(第二种方式)
在 src下新建 setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
createProxyMiddleware("/api",{
target:"http://localhost:8888/",
changeOrigin:true,
pathRewrite: {
"^/api": ""
}
})
)
}
(3) 新建server.js
yarn init -y
yarn add express nodemon -D
const express = require("express");
const app = express();
app.get("/user",(req,res) =>{
let obj = {
name: '张三',
age: 20,
gender: '男'
}
res.send(obj)
})
const port = 8888;
app.listen(port,()=>{
console.log(`端口启动 http://localhost:${port}`);
})
启动
npx nodemon server.js
(4) 请求后端数据
yarn add axios -D
import React, { Component } from 'react'
import axios from 'axios'
export default class App extends Component {
constructor() {
super()
this.state = {}
}
getData = () =>{
console.log(process.env)
axios.get("/api/user").then(res =>{
console.log('res====',res)
})
}
componentDidMount() {
this.getData()
}
render() {
return (
<div>
<h1>hello react-cors</h1>
</div>
)
}
}