构建Wep App 2018(三)|前后端跨域资源共享|Cors+Axios+Vue+Express

前言

为解决Vue前端与Node.js服务端端数据请求传输问题,由于服务端和前端端口不同,数据请求跨域,故使用Axios与Cors实现Ajax跨域通信。

Vue前端:"http://localhost:8080"
Node.js服务端:"http://localhost:3000"


服务端配置

  • 安装Cors组件
npm install cors --save
  • 服务器跨域设置
    main.js
var express = require("express");
var cors = require("cors");
var app = express();

app.use(
  cors({
    origin: ["http://localhost:8080"],
    methods: ["GET", "POST"],
    alloweHeaders: ["Content-Type", "Authorization"]
  })
);

app.get("/getNewsList", function(req, res, next) {
  res.send("get /getNewsList");
  console.log("get /getNewsList");
});

app.get("/vueTest", function(req, res, next) {
  res.send("get /vueTest");
  console.log("get /vueTest");
});
app.listen(3000);
console.log("[Listening on port 3000...");

也可添加以下命令,允许任意跨域访问

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();
});


前端配置

  • 安装axios组件
npm install axios --save
  • 安装cors及vue-cors组件
npm install cors --save
npm install vue-cors --save
  • 配置前端入口脚本
    main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue";
import App from "./App";
import router from "./router";
import axios from "axios";
import VueAxios from 'vue-axios'
import Vuetify from "vuetify";
import "vuetify/dist/vuetify.min.css";


Vue.use(VueAxios,axios);
Vue.use(Vuetify);

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  components: { App },
  template: "<App/>"
});
  • 测试
    在服务端app.js中添加
app.get("/getNewsList", function(req, res, next) {
  res.send("get /getNewsList");
  console.log("get /getNewsList");
});

app.get("/vueTest", function(req, res, next) {
  res.send("get /vueTest");
  console.log("get /vueTest");
});

在任一components中加入

<script>
export default {
  name:'vcardNews',
  data(){
      return{
          clists:[]
      }
  },
  methods:{
    /*
      https://www.npmjs.com/package/vue-axios
    */
    getNewsList(){
      this.axios.get('http://localhost:3000/getNewsList').then((response) => {
        alert(response.data);
        this.clists = response.data;
      })
    }
  },

  mounted(){
    this.getNewsList()
  }
}
</script>
  • 测试成功



©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 以下是盖茨先生的十条玉言,经常阅读,我认为大有好处。 1 . 社会充满不公平现象。你先不要想去改造它,只能先适应它...
    BUG弄潮儿阅读 3,304评论 0 0
  • 老姐打来电话,开始就是稀里哗啦的一通抱怨。说感觉现在整天都不知道干什么,一天也就几节课,闲时间很多,却愣是不知道干...
    jiao我树人阅读 2,885评论 0 0
  • 和你相识,已经快六年了。在这将近六年的时间里,我不得不承认,你带给我更多的是快乐。我也忘记,当初我和你是如何相识...
    不想睡觉的豆子阅读 4,320评论 0 3