Node--Vue--解决跨域问题

  1. 什么是跨域?
    跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。
    同源就是指,域名、协议、端口均为相同。
    例如:
    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都指向本机,但也属于跨域。

  2. 解决方案
    前端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

=========================================================
成功解决!在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值