vue+express+mysql搭建博客時,使用axios進行前後臺數據交互時,出現GET http://localhost:8080/api/getArticle 504 (Gateway Timeout) 或者GET http://localhost:8080/api/getArticle 404 (Not Found),找了很久才解決,所以寫個博客記錄一下用到的方法或者相關方法
1.跨域:這個是一開始遇到的,解決有很多教程
(1)在項目中的config => index.js中的ProxyTable設置
// config/index.js中
proxyTable: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true, //允許跨域
pathRewrite: {
'^/api': ''
}
}
// server/index.js中
const express = require('express');
const app = express();
app.get('/api/getArticle', (req, res, next) => {
res.json({
data: '後臺返回結果 getArticle'
})
})
// 監聽端口
app.listen(3000); //後臺運行在3000端口
console.log('success listen at port:3000......');
// component/note.vue中
methods: {
getArticle (){
this.axios.get('/api/getArticle')
.then( (res) => {
console.log('res', res);
this.message = res.data.data;
})
}
}
按照如上設置,就可以解決跨域問題
2.如何跨域實現後,還是出現一開始的問題,那麼有可能是你的後臺端口沒有打開,在cmd中,進入server目錄,運行server/index.js文件
cd blog //進入項目文件
cd server //使用node文件
cd index.js //使用node搭建的服務器
node index.js //運行文件,打開後臺端口
端口打開後,再重新刷新頁面就可以了。