Davide Cremona
Davide Cremona

Reputation: 121

Nodejs local API does not work

I'm doing an university project with NodeJs but I have some trouble in testing it in local.

This is the problem: I have a GET API "/api/services/names" and the NodeJS server is running on port 8080.

If I test the API with Postmanor by putting the URL in the Chrome bar ("http://localhost:8080/api/services/names") it works fine and I can get my response.

The problem is that if I test it in my local website using fetch() inside this function:

function fetchServicesNames(){
    fetch('/api/services/names')
        .then(function(response){
            return response.json();
        })
        .then(function(data){
            data.map(addServiceLink);
        });
}

The Javascript console gives me this error:

Failed to load resource: the server responded with a status of 404 (Not Found)

I noticed that when I hover the console error, it shows the request string "http://localhost/api/services/names" without the port. But I don't think this is the problem because when I deploy the application on the Heroku platform it works fine... the problem is just in localhost (I'm working with a mid 2010 macbook pro with Mac OSX 10.10.2).

Any help is appreciated, thank you in advance.

Edit: as requested I'm adding here the server code

// server.js for Hypermedia Application project.

// BASE SETUP
//============================================================

// call packages
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');

app.use(express.static(__dirname + "/public"));

// we use body-parser, so we need to be able to read data either from 
// GET and POST:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


// setting the application port to listen 
var serverPort = process.env.PORT || 5000;

// --- database connection omitted ---

// API ROUTES
// ================================================================
// first of all: get the Router
var router = express.Router();

/**
 * Services names
 * /api/services/names  - get   - get all services ids and names
 */
router.route('/services/names')
.get(function (req, res) {

    Service.find({}, 'id name', function (err, services) {

        if (err)
            res.send(err);

        res.json(services);
    });  

});

// --- Other APIs omitted ---

// REGISTER ROUTES:
// all of our routes will be prefixed with /api
app.use('/api', router);


// START THE SERVER
//===================================================================
app.set("port", serverPort);

app.listen(serverPort, function() {
    console.log(`Your app is ready at port ${serverPort}`);
});

Upvotes: 2

Views: 3214

Answers (3)

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6512

at your server page you add

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

before your API's

it might help you for CORS

Upvotes: 4

Deepak M
Deepak M

Reputation: 849

Hi try modifying the line like fetch('http://'+window.location.host+':8080/api/services/...)

Upvotes: -1

Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6512

Dear i suggest you to write total Path like

http://localhost:<your port number>/api/services/names

inside fetch()and u check once

I too tried and i got Success

Upvotes: -1

Related Questions