1

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.

1
  • I just found out that i am trying to reach localhost on the laptop that is not hosting the api. Ive looked so long at this that i was not seeing the obvious. Commented Dec 21, 2023 at 22:13

2 Answers 2

0

There are two main issues, the first one is in the following part of the snippet

//...
if (req.body = {} || !req.body) {
    res.status(418).send({message:'We need a json'})
    return
}
//...

apparently what you're trying to do is to check weather the req.body object is empty or not, but by doing this req.body = {} you're assigning an empty object to req.body, this expression req.body = {} is a truthy expression, meaning that the code inside the if block will be executed anyways, you can instead either use Object.keys(req.body).length to check weather the object is empty or not, or check for a specific key as follows:

//...
const requestBody = req.body || {};
if ("data" in requestBody) {
    res.status(200).send({
        machine: `dit is je machine met je json ${req}`,
    });
    return;
}

    res.status(418).send({ message: "We need a json" });
//...

the client code

fetch('http://localhost:98/machines', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*'
    },
    body: JSON.stringify({data: "request data"})
    //...

The second problem is in corsOptions, try this:

const corsOptions = {
    origin: ["http://192.168.1.99:94", "http://127.0.0.1:94"],
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thats a realy good tip thanks!
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.