使用axios解决‘Access-Control-Allow-Origin’跨域

引入axios
回到vue脚手架工程,输入命令

npm i axios

在src/axios/目录下创建index.js

import Vue from 'vue'
import axios  from 'axios' 

axios.defaults.baseURL="http://localhost:3000"
Vue.prototype.$ajax = axios

在main.js中引入axios

import './axios'

发送Ajax请求
接下来修改login.vue,在login方法中发送ajax请求

login() {
    this.$refs.loginForm.validate((valid) => {
        if (valid) {
            this.$ajax.post('/users/validate', this.user).then((res) => {
                if (res.data) {
                    this.$store.dispatch('login', res.data).then(() => {
                        this.$notify({
                            type: 'success',
                            message: '欢迎你,' + res.data.name + '!',
                            duration: 3000
                        })
                        this.$router.replace('/')
                    })
                } else {
                    this.$message({
                        type: 'error',
                        message: '用户名或密码错误',
                        showClose: true
                    })
                }
            }).catch((err) => {
                this.$message({
                    type: 'error',
                    message: '网络错误,请重试',
                    showClose: true
                })
            })
        }
        else {
            return false
        }
    })
}
解决’Access-Control-Allow-Origin’跨域问题
修改完毕后启动数据,后端服务器,进行登录,结果发现会提示网络错误 

打开浏览器调试工具,发现报以下错误

Failed to load http://localhost:3000/users/validate: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8080' is therefore not allowed access.

这是因为http请求头部没有进行允许跨域导致的,打开后端服务的app.js文件,在路由配置前添加以下代码

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});

// 以下是之前的路由配置代码
app.use('/users', router)

修改之后再重新启动后端服务器进行登录,完成功能 
 

猜你喜欢

转载自blog.csdn.net/LanSeTianKong12/article/details/84938047
今日推荐