react项目配置mockjs、跨域配置,模拟后台接口

本地跨域配置

  1. react porxy 只代理一个,修改package.json文件,新增
	"proxy":"http://172.19.5.35:9536",

在这里插入图片描述
2 react porxy 代理多个
在这里插入图片描述
3.可以修改node_modules/react-scripts/config/webpackDevserver.config.js 下面代码,添加跨域配置
在这里插入图片描述
代码如下:

 proxy: {
        '/api/': {
		       target: 'http://172.16.136.249:8080', // 目标服务器 host
		       secure: false, 
		       changeOrigin: true, // 默认false,是否需要改变原始主机头为目标URL
		       ws: false, // 是否代理websockets
		       pathRewrite: { // 重写请求,比如我们源访问的是api/data,那么请求会被解析为/api/index/data
		      		"/api": "/api/index" 
	    	   },
	    	   router: {
	            // 如果请求主机 == 'dev.localhost:3000',
	            // 重写目标服务器 'dev.localhost:3000' 为 		 'http://localhost:8000'
	            'dev.localhost:3000' : 'http://localhost:8000'
	         }
        }
   },

使用express+mock整合来实现的动态模拟接口。

(1)首先需要安装express

	npm install express  --save;

(2)在react 根目录下新建mock文件夹,里面新建 server.js

    var express = require("express")
	var app = express();
	var bodyParser = require('body-parser');
	var Mock = require("mockjs")
	app.use(bodyParser.json());  //body-parser 解析json格式数据
	app.use(bodyParser.urlencoded({            //此项必须在 bodyParser.json 下面,为参数编码
	    extended: true
	}));

	var router = express.Router();
	
	app.get('/', function(req, res) {
	    res.send('hello world');
	});
	
	// router.use("/test",require('./test'));
	// 以下就是模拟的接口--profile
	router.use("/api/profile",function (req,res) {
	    console.log(req.body);
	    //调用mock方法模拟数据
	    var data = Mock.mock({
	            // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
	            'list|1-10': [{
	                // 属性 id 是一个自增数,起始值为 1,每次增 1
	                'id|+1': 1
	            }]
	        }
	    );
	    return res.json(data);
	})
	app.use("/api",router)
	
	app.listen(3001)

(3)启动服务命令:

第一种:在当前项目目录执行

node mock/server.js

第二种,因为我们使用npm管理包,在 package.jsonscripts 加入

"mock": "node ./mock/server.js"

只需要执行 npm run mock 启动服务就可以了哦~~

npm run mock

在浏览器的输入http://localhost:3001/api/test/profile即可看到输出的JSON数据列表,

	fetch('/api/profile', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        // mode: 'no cors',
        // cache: 'default'
    })
    .then(res => res.json())
    .then((data) => {
        console.log(data, 111)
    })

!!!需要注意的是,接口名称要与配置跨域的地址对上,文章中配置的跨域地址,需要稍微改动一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章