前端解决跨域问题方法:
1、在返回头加入headers: { "Access-Control-Allow-Origin": "*" }
let { pathname, query } = url.parse(req.url, true); // true把query转化成对象
if (pathname === '/page') {
let offset = parseInt(query.offset) || 0; //拿到当前前端传递的值
read(function(books) {
// 每次偏移量 在偏移的基础上增加五条
let result = books.reverse().slice(offset, offset + pageSize); //数据倒序
let hasMore = true; //默认有更多
if (books.length <= offset + pageSize) { // 已经显示的数目 大于了总共条数
hasMore = false;
}
res.setHeader('Content-Type', 'application/json;charset=utf8');
res.setHeader("Access-Control-Allow-Origin", "*");
res.end(JSON.stringify({ hasMore, books: result }));
});
return;
}
2、使用node解决跨域问题
//app.js
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
3.使用node koa框架 引入cors
npm install cors
//app.js
let cors = require('cors');
app.use(cors());
网友评论