express+vue跨域问题

2 篇文章 0 订阅
2 篇文章 0 订阅

新建文件夹express_vue
分别新建两个子文件夹:server与web存放后端与前端项目

一、在server文件夹下

  • 执行express-generator npm install express-generator -g全局安装脚手架
  • express --version 来检测一下是否安装成功
  • 执行express express_server创建一个文件夹名为express_server的express项目
  • 进入express_server文件夹下执行npm install安装相关依赖
  • 执行npm starts可以启动项目,进入浏览器打开http://localhost:3000

在这里插入图片描述

  • 在routes文件夹下新建一个login.js文件,相关代码如下
var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {
    let data = {
        code: 200,
        result: {
            name: 'chen',
            password: '123'
        },
        msg:'请求成功'
    }
    res.json(data)
});

module.exports = router;

在app.js文件里
这些代码是在别人访问http://localhost:3000/login这个路径去读取login文件并返回相关数据

var getLogin= require('./routes/login')
app.use('/login', getLogin)

因为是前后端分离开发,所以这里后有个跨域问题,一般使用cors解决跨域
在项目里执行npm install cors --save
安装cors依赖
在app.js文件下,导入依赖,并设置相关配置,不熟悉cors的同学可以去查看相关代码,下面的这些代码一定要写在上面,不能写在app.use(’/login’, getLogin)下面,
不然返回数据的时候会报错Failed to load http://localhost:3000/get_article_list: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:8080’ is therefore not allowed access.
HelloWorld.vue?18db:24 22Error: Network Error

const cors = require('cors')
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')
  res.header('X-Powered-By', ' 3.2.1')
  next()
})
app.use(cors({
  origin:['http://localhost:8080'],
  method:['GET','POST']
}))

二、在web文件夹下

  • 执行npm install -g vue-cli全局安装vuecli2脚手架
  • 执行vue init webpack ‘项目名’
  • 安装完成之后执行npm install 安装相关依赖
  • 如果还没安装axios的需要
  • 执行npm install axios 安装axios
  • 在holloword.vue文件夹修改
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>{{data.name}}</p>
    <span>{{data.password}}</span>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      data: {}
    }
  },
  created() {
    axios.get('http://localhost:3000/login').then(res=>{
      if(res.data.code){
        this.data = res.data.result
      }
    }).catch(err =>{
      console.log(err);
    })
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

成功的效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值