node后端與Vue前端跨域處理方法詳解
node.js后端跨域解決方案
先看后端的入口文件:
app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
const expressJWT = require('express-jwt')
const app = express();
const users = require('./routes/users')
const config = require('./config')
app.use(expressJWT({secret: config.jwtSecretKey}).unless({path: [/^\/api\/users/]}))
// const db = require('./db/index')
app.use(cors())
app.use(express.urlencoded({extended: false}))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.send('hello world !')
})
app.use('/api/users', users)
const testRouter = require('./routes/testToken')
app.use('/my', testRouter)
const profiles = require('./routes/profiles')
app.use('/api/profiles', profiles)
app.use((err, req, res, next) => {
if (err) return res.send({status: 400, message: err})
if(err.name === 'UnauthorizedError') return res.send({status: 404, message: '身份認(rèn)證失敗'})
res.send({status: 404, message: err})
})
app.listen(5000, () => {
console.log('api server running at http://127.0.0.1:5000')
})代碼不少,但重要的就下面這幾行:
const cors = require('cors')
app.use(cors())
前提條件是你得先安裝了cors,這樣寫(xiě)好之后,就保證你的后端接口可以跨域訪問(wèn)了。
前端vue項(xiàng)目
前端要發(fā)起ajax請(qǐng)求,可以在入口文件main.js中全局掛載axios,而后端的接口則最好寫(xiě)在axios.defaults.baseURL中
main.js
import Vue from 'vue'
import App from './App.vue'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import router from './router'
import axios from './http'
Vue.use(ElementUI);
axios.defaults.baseURL = 'http://127.0.0.1:5000/api/'
Vue.prototype.$axios = axios;
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')注意注意注意,最重要的代碼是:axios.defaults.baseURL = 'http://127.0.0.1:5000/api/'
這行代碼是前端項(xiàng)目能跨域的關(guān)鍵
注意import axios from './http'引入的是我自己寫(xiě)的http.js
http.js
import axios from "axios";
import { Message, Loading } from 'element-ui';
let loading;
function startLoading(){
loading = Loading.service({
lock: true,
text: '數(shù)據(jù)加載中',
background: 'rgba(0,0,0,0.7)'
})
}
function endLoading(){
loading.close();
}
// 請(qǐng)求攔截
axios.interceptors.request.use(config => {
startLoading();
return config
}, error => {
return Promise.reject(error)
})
//響應(yīng)攔截
axios.interceptors.response.use(response => {
endLoading();
return response
}, error => {
endLoading();
Message.error(error.response.data)
return Promise.reject(error)
})
export default axios這里寫(xiě)了一些請(qǐng)求攔截和請(qǐng)求響應(yīng)的代碼,也可以不寫(xiě),主要是有一些請(qǐng)求的動(dòng)畫(huà)。這個(gè)文件主要的作用是引入了axios
前端axios請(qǐng)求
methods: {
submitForm(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
this.$axios
.post("/users/register", this.registerUser)
.then(res => {
// 注冊(cè)成功
this.$message({
message: "注冊(cè)成功!",
type: "success"
});
// this.$router.push("/login");
});
} else {
console.log("error submit!!");
return false;
}
});
}
}這就是常規(guī)的axios請(qǐng)求了
post("/users/register", this.registerUser)可以保證請(qǐng)求到http://127.0.0.1:5000/api//users/register中后端接口的數(shù)據(jù),這里是post請(qǐng)求,即向后端提交數(shù)據(jù)。
到此這篇關(guān)于node后端與Vue前端跨域處理方法詳解的文章就介紹到這了,更多相關(guān)node跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
nodejs簡(jiǎn)單實(shí)現(xiàn)操作arduino
本文給大家分享的是使用nodejs來(lái)驅(qū)動(dòng)arduino,主要是基于cylonjs 和 gort,有需要的小伙伴可以參考下2016-09-09
Node.js中如何合并兩個(gè)復(fù)雜對(duì)象詳解
下面這篇文章主要給大家介紹了在Node.js中如何合并兩個(gè)復(fù)雜對(duì)象的方法,文中給出了詳細(xì)的示例代碼,相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友可以參考,下面來(lái)一起看看吧。2016-12-12
node如何實(shí)現(xiàn)cmd彈窗交互之inquirer
這篇文章主要介紹了node如何實(shí)現(xiàn)cmd彈窗交互之inquirer問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
在Node.js中使用Express框架和Mongoose庫(kù)實(shí)現(xiàn)視頻評(píng)論功能
本文我們將詳細(xì)介紹如何在Node.js應(yīng)用中使用Express框架和Mongoose庫(kù)來(lái)實(shí)現(xiàn)一個(gè)視頻評(píng)論功能,這個(gè)功能允許用戶對(duì)視頻內(nèi)容添加評(píng)論,并將評(píng)論數(shù)實(shí)時(shí)更新,以下是逐步的實(shí)現(xiàn)過(guò)程,包括代碼示例和說(shuō)明,需要的朋友可以參考下2024-04-04
nodeJS服務(wù)器的創(chuàng)建和重新啟動(dòng)的實(shí)現(xiàn)方法
今天小編就為大家分享一篇nodeJS服務(wù)器的創(chuàng)建和重新啟動(dòng)的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05

