React(创建简单本地服务器获取数据测试和配置网络代理)解决跨域

一.创建简单的本地服务器获取数据

1.首先使用npm安装expres

然后写文件

const { response } = require('express')
const express = require('express');
const { request } = require('http');
const app = express()

app.use((request,response,next)=> {
    console.log('有人请求服务器1');
    next()
})

app.get('/students',(request,response)=> {
    const students = [
        {id:'001',name:'tom',age:18},
        {id:'002',name:'mali',age:25},
        {id:'003',name:'tony',age:15},
    ]
    response.send(students)
})

app.listen(5000,(err)=> {
    if(!err) {
        console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:5000/students');
    }
})

启动方式:

node ./server1.js

二.在react配置网络代理(可支持多个代理)

1.首先在src目录下创建setupProxy.js(这个文件用来配置网络代理)

配置好后,需要重启项目才生效

const proxy = require('http-proxy-middleware')

module.exports = function(app) {
    app.use(
        proxy.createProxyMiddleware('/api',{ //遇见/api前缀的请求,就会触发改代理配置
            target:'http://localhost:5000', //请求转发给谁
            changeOrigin:true, //控制服务器收到的请求头中Host的值
            pathRewrite:{'^/api':''}//重写请求路径(必须)
        })
        // 下面如果要配置多个代理,可以按照上面的形式配置
    )
}

 之后控制台上可以看见请求到了数据

猜你喜欢

转载自blog.csdn.net/weixin_62639453/article/details/127834400
今日推荐