新建server文件夹,npm init初始化项目,建立demo.js文件
1.目录结构:
2. demo.server.js内容:
const express = require("express");
const app = express();
var allowCors = function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Credentials", "true");
next();
};
app.use(allowCors); //使用跨域中间件
const arr = [
{ id: 101, content: [{ id: "101", text: "101" }] },
{ id: 100, content: [{ id: "100", text: "100" }] }
];
// 模拟字符串数据
app.get("/user/:id", (req, res) => {
let urlId = req.params.id;
let data = arr.find(item => item.id == urlId);
res.send(data.content);
});
app.listen(3001, () => console.log("Example app listening on port 3001!"));
3.fetch请求,因为存在跨域,所以在package.json中配置
"proxy":"http://localhost:3001"
/**
* 获取待办事项初始数据
*/
export const fetchTodos = () => {
return dispatch => {
dispatch(fetchTodosRequest());
return fetch("http://192.168.3.130:3001/user/101").then(
response => {
response.json().then(data => {
dispatch(fetchTodosSuccess(data));
});
},
error => {
console.log(222);
dispatch(fetchTodosFailure(error));
console.log("An error occurred: " + error);
}
);
};
};
下面展示 post请求 demo-server.js 和 fetch请求的写法
- demo-server.js:
req.query获取不到传过来的参数,因此需要在app.js中使用json解析中间件(body-parser)
const express = require("express");
var bodyParser = require("body-parser");// 引入json解析中间件
const app = express();
var allowCors = function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Credentials", "true");
next();
};
app.use(allowCors); //使用跨域中间件
// 添加json解析
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
const arr = [
{ id: 101, content: [{ id: "101", text: "101" }] },
{ id: 100, content: [{ id: "100", text: "100" }] }
];
// 模拟字符串数据
app.post("/user", (req, res) => {
let urlId = req.body.id;
let data = arr.find(item => item.id == urlId);
res.send(data.content);
});
app.listen(3001, () => console.log("Example app listening on port 3001!"));
fetch.js
/**
* 获取待办事项初始数据
*/
export const fetchTodos = () => {
return dispatch => {
dispatch(fetchTodosRequest());
return fetch("http://192.168.3.130:3001/user",{
method:'POST',
body:JSON.stringify({id:100}),
headers: {
'content-type': 'application/json'
},
}).then(
response => {
response.json().then(data => {
dispatch(fetchTodosSuccess(data));
});
},
error => {
dispatch(fetchTodosFailure(error));
}
);
};
};