Jake quin
Jake quin

Reputation: 742

How to access a rest api in the local network using node js and express

I have created a REST server using Node.js and express, but i am having trouble connecting to the server on a separate machine. The server machine and client machine are on the same local network.

This is my code for the server

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

const PORT = process.env.PORT || 3000;

const imageUpload = require("./routes/imageUpload");

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', '*');
    next();
});

app.use("/imageUpload", imageUpload);

app.listen(PORT, "0.0.0.0", () => {
    console.log("Running at port " + PORT);
})


router.get("/getFilename", (req, res) => {

        res.status(200).json({
            status: "recieved"
        });
 });

Upon using postman on the server machine the get request works fine even if using the machine IP address in the network(192.168.0.104:3000/imageUpload/getFilename).

On a separate machine in the network the postman will give an error of There was an error connecting to 192.168.0.104:3000/imageUpload/getFilename. so i am unable to connect to the API, How do i fix this? Thank you very much

Upvotes: 0

Views: 4480

Answers (1)

Pavel K
Pavel K

Reputation: 370

Your problem is rather in network settings, not in nodejs or express.

Did you try ping 192.168.0.104 your server? If it works most likely you need to manually open port 3000.

Try google how to open a port on a server for the OS your are using on that machine.

Upvotes: 2

Related Questions