-
什么是跨域?
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。
同源就是指,域名、协议、端口均为相同。
例如:
http://www.111.com/index.html 调用 http://www.111.com/server.php
(非跨域)
http://www.111.com/index.html 调用 http://www.222.com/server.php
(主域名不同:111与222不同,跨域)
http://aaa.111.com/index.html 调用 http://bbb.111.com/server.php
(子域名不同:aaa与bbb不同,跨域)
http://www.111.com:8000/index.html 调用 http://www.111.com:5000/server.php
(端口号不同:8000/5000,跨域)
http://www.111.com/index.html 调用 https://www.111.com/server.php
(协议不同:http/https,跨域)
注:localhost和127.0.0.1都指向本机,但也属于跨域。 -
解决方案
前端vue代码:main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import Axios from 'axios'
Axios.defaults.baseURL = "http://localhost:8081"
Vue.prototype.$axios = Axios
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
store
}).$mount('#app')
home.vue调用
created() {
this.$axios.get('/home')
.then(function (res) {
console.log(res);
})
.catch(function (err) {
console.log(err);
});
}
后端node代码:
app.js
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const router = require('./router')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
//跨域问题解决方案
const cors = require('cors');
app.use(cors({
origin:['http://localhost:8080'],
methods:['GET','POST'],
}));
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8080');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
next();
})
//=================
app.use(express.static(path.resolve(__dirname, '../dist')));
app.use(router)
app.listen(8081, function () {
console.log('success listen...8081');
});
router.js
const express = require('express')
const router = express.Router()
router.get('/home', function (req, res) {
let data = {
code:0,
data:{name:'Franklin',pwd:8888},
isSuccess:true,
msg:'successful!'
};
res.json(data);
});
module.exports = router
=========================================================
成功解决!