最近開始搭建個(gè)人博客, 遇到的第一個(gè)問題是跨域問題, 因?yàn)樽詈蠛喜⒌揭粋€(gè)項(xiàng)目里需要臨時(shí)跨域. 需要解決下臨時(shí)跨域的問題.
Vue.axios.get('http://192.168.4.14:3000/index').then((response) => {
console.log(response.data)
}
解決跨域問題的方法有很多, 此次添加中間件設(shè)置header的方式解決跨域
//設(shè)置跨域訪問
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();
});
添加一個(gè)中間件在所有需要跨域的路由之前即可
例:
后臺(tái)設(shè)置index路由
const express = require('express');
const router = express.Router();
//設(shè)置跨域訪問
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)
});