Search code examples
javascriptnode.jsfetch-apiput

Can't do Put requests on API hosted on my laptop and executed on another laptop


I just couldn't find the answer to my problem online and I hope someone can help me. I made an API with nodejs and express (with some help from YouTube and Google). I was able to do some get and put requests on localhost. I also was able to do a GET request on a different laptop, but as soon as I tried the PUT request on a different laptop it doesn't even reach the server and it gives me a rejected promise.

  • I tried to turn of my firewall just to be sure.
  • I also tried postman, and postman was able to reach the API and do the PUT request.

Here is some code that might give some more context: API (with an empty string sent it should give back a 418 code):

const { getAllSoftware, updateMachines } = require('./services/db');
const express = require('express');
const cors = require('cors'); // Import CORS middleware
const app = express();
const PORT = 98;

// CORS configuration
const corsOptions = {
    origin: ['http://192.168.1.99:94', 'http://localhost:94'], // Update with your client's domains
};

app.use(cors(corsOptions)); // Use CORS middleware

app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

app.use(express.json());

app.put('/machines', async (req, res) => {
    console.log(req.body);
    if (req.body = {} || !req.body) {
        res.status(418).send({message:'We need a json'})
        return
    }

    res.status(200).send({
        machine: `dit is je machine met je json ${req}`
    })

});

API CALL from different laptop (localStorageData is an empty JSON string {})

fetch('http://localhost:98/machines', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*'
    },
    body: JSON.stringify(localStorageData)
    })
    .then(response => {
    // Handle the response here
    console.log(response);
    })
    .catch(error => {
    // Handle errors here
    console.error('Error:', error);
    });
}

If there is more information needed, please let me know :) API's are a bit of new territory for me, and I am eager to learn how I can make this work correctly.


Solution

  • The reason why I couldn't reach my host computers API was because i was trying to reach localhost:98. And as far as i know it isn't possible to reach localhost from a different laptop like this.

    The solution was to set the url to my host computers ip adress.