本地跨域配置
- 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.json 的 scripts 加入
"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)
})
!!!需要注意的是,接口名稱要與配置跨域的地址對上,文章中配置的跨域地址,需要稍微改動一下。