最近开始搭建个人博客, 遇到的第一个问题是跨域问题, 因为最后合并到一个项目里需要临时跨域. 需要解决下临时跨域的问题.
Vue.axios.get('http://192.168.4.14:3000/index').then((response) => {
console.log(response.data)
}
解决跨域问题的方法有很多, 此次添加中间件设置header的方式解决跨域
//设置跨域访问
router.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();
});
添加一个中间件在所有需要跨域的路由之前即可
例:
后台设置index路由
const express = require('express');
const router = express.Router();
//设置跨域访问
router.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();
});
/* GET home page. */
router.get('/index', function(req, res, next) {
// res.render('index', { title: 'Express' });
res.send('跨域请求')
});
module.exports = router;
前端使用 axios请求
const cityGuess = () => Vue.axios.get('http://localhost:3000/index').then((response) => {
console.log(response.data)
});
网友评论