简体   繁体   English

Vue:使用 vue-cli 将请求代理到单独的后端服务器

[英]Vue: Proxy requests to a separate backend server with vue-cli

I am using vue-cli webpack template to generate my projects, and I'd like to proxy requests to a separate, backend server.我正在使用 vue-cli webpack 模板来生成我的项目,并且我想将请求代理到一个单独的后端服务器。 But I got the error message as follow.但我收到如下错误信息。

Could anyone tell me what's the matter with my coding?谁能告诉我我的编码有什么问题?

Thank you very much!非常感谢!

Error message错误信息

[HPM] Error occurred while trying to proxy request from localhost:8080 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

config -> index.js配置 -> index.js

proxyTable: {
'/api':{
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
    '^/api': ''
    }
 }

src -> main.js src -> main.js

import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import routerConfig from './router.config.js' 
import Axios from 'axios'


Vue.config.productionTip = false;
Vue.prototype.$axios = Axios;
Vue.prototype.HOST = '/api';

Vue.use(VueRouter);

const router = new VueRouter(routerConfig) 

new Vue({
 el: '#app',
 router,  
 components: { App }, 
 template: '<App/>',
})

src -> App.vue src -> App.vue

export default{

created(){
  var url = this.HOST
  this.$axios.get(url,{

  }).then((res)=>{

   console.log(res.data)

  },(res)=>{

  alert(res.status)
  })
 }
}

server服务器

const express = require('express');
const mysql = require('mysql');

const db = mysql.createPool({
  localhost:'localhost',
  user:'root',
  password:'123456',
  database:'blog'
})

const server = express();

server.use('/api',(req,res)=>{

db.query(`SELECT * FROM articles_table`,(err,data)=>{
   if(err){
     console.error(err);
     res.status(500).send('database error').end();
   }else{
     res.send(data)
   }
 })

})
server.listen(3000)

Do as follows:执行以下操作:

npm install --save-dev concurrently

Add to scripts at package.json:添加到 package.json 中的scripts

"server": "node server.js",
"go": "concurrently --kill-others \"npm run dev\" \"npm run server\""

And use, from now on:并使用,从现在开始:

npm run go

Naturally, you can rename go to whatever you want.当然,你可以重命名go任何你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM