5

I recently started learning vue.js and currently using vue.js with vue-simple-webpack template , express and mongo to develop a simple application . I am using localhost to develop and test the application.

application front-end runs in port 8080 and the server is running in a different port (3000)

Here is my server.js where i have a simple api to get data from my localdb

const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const mongodb = require('mongodb');
const bodyParser= require('body-parser');
const app = express();
var db;

var URL='mongodb://localhost:27017/'+'mydb';
console.log(URL);

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())

MongoClient.connect(URL, (err, database) => {
  if (err) 
    return console.log(err);
  db = database;
  app.listen(3000, () => {
    console.log('listening on 3000');
  })
})

app.get('/products', (req, res) => {
    db.collection('products').find().toArray(function(err, results) {
    console.log(results)
    res.setHeader('Content-Type', 'application/json');
    res.send(JSON.stringify(results));
    })
})

tested the server.js , it works . see below screenshot.

enter image description here

Vue application is running in http://localhost:8080/ using the webpack template's default configuration. i am trying to call the /products api end from the vue.js file using $http get as follows...

export default {
  name: 'Products',
  methods: {
        get: function() {
            // GET request
            this.$http({
                url: '/products',
                method: 'GET'
            }).then(function(response) {
                console.log('ok');
            }, function(response) {
                console.log('failed');
            });
        }
    }
}

But i get the following error in the browser console.

enter image description here

As you can see , even though i am using the port 3000 in server.js , when i try access the /products api end , it actually goes through port 8080. Therefore it throws a 404 http error .

My question is how i can access the API end from within the front-end which runs in a different port. Is that even possible ?

Can i use API Proxying here . If so , can somebody point me in the correct direction on how to do it since there are not much info available on the web.

Malik
  • 3,520
  • 7
  • 29
  • 42

1 Answers1

7

You can use proxy configuration provided by webpack.

Docs: https://webpack.js.org/configuration/dev-server/#devserver-proxy

snippet config:

proxy: {
  "/products": "http://localhost:3000/products"
}

A better practice would be forwarding /api/* requests to http://host:port/api/* urls.

Saurabh Nemade
  • 1,522
  • 2
  • 11
  • 20
  • I added the proxy in the webpack web config . Also changed server urls to /api/* pattern like you suggested . But the issue is still there when i try to access the /api/products . the $http.get method tries to access the /api/products from within the localhost:8080 port . therefore i am getting the 404 error – Malik Oct 18 '17 at 07:04
  • Please refer this issue i have raised in my code github code repo. https://github.com/mal90/adApp/issues/3 – Malik Oct 18 '17 at 08:27
  • You can add following config. I just checked out the code and tested. It worked fine. :) proxy: { "/api/": { target: "http://localhost:3000/", secure: false } } – Saurabh Nemade Oct 18 '17 at 10:14
  • Correct . that works . In my early solution with proxy , i made a mistake . Thank you @Saurabh – Malik Oct 18 '17 at 10:22
  • 1
    This is brilliant, and by far the most simple solution to this whole CORS problem. – Marco Jan 27 '21 at 15:44