Sylvia
Sylvia

Reputation: 277

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. 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

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

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

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)

Upvotes: 3

Views: 3359

Answers (1)

acdcjunior
acdcjunior

Reputation: 135762

Do as follows:

npm install --save-dev concurrently

Add to scripts at package.json:

"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.

Upvotes: 1

Related Questions