failed to fetch data from localhost

Issue

I made my first API with NodeJs

this is what i get if i try to access to the resource from the url of the browser

enter image description here

I succed to access to posts with postman.
Now i tried to set a little call with a graphic site, but I wasn’t able to fetch the datas

this is the call that i tried in a saga

export const fetchWrapper = async url => {
  var request = new Request({
      url: url,
      method: "GET"
  });
  await fetch(request)
      .then(res => res.json())
      .then(
          result => {
              return result;
          },
          error => {
              return error;
          }
      );
};

and this is the saga

export function* getPosts() {
    const url = `http://localhost:8080/feed/posts`;
    try {
        const  data  = yield call(fetch(url), {method: 'GET'});
        console.log('data',)
        yield put(getPostsResponse({ data }));
    } catch (e) {
        console.log("error", e);
    }
}

and these are the errors that i have in the console

enter image description here

enter image description here

UPDATE

As suggested in the comment this is my node code

controller/feed.js

exports.getPosts = (req, res, next) => {
    res.json({
        posts: [
            { id: 1, title: "Titolo 1", description: "descrizione 1" },
            { id: 2, title: "Titolo 2", description: "descrizione 2" },
            { id: 3, title: "Titolo 3", description: "descrizione 3" }
        ]
    });
};

exports.createPosts = (req, res, next) => {
    const title = req.body.title;
    const description = req.body.description;

    const ID = 1234;

    res.status(201).json({
        message: "success operation",
        post: {
            id: ID,
            title: title,
            description: description
        }
    });
};

route/feed.js

const express = require("express");
const router = express.Router();

const feedController = require("../controllers/feed");

router.get("/post", feedController.getPosts);
router.post("/post", feedController.createPosts);


module.exports = router;

app.js

const express = require('express');
const bodyParser = require("body-parser");
const feedRoute = require('./route/feed');

const app = express();

app.use(bodyParser.json()); //application json
app.use('/feed', feedRoute);
app.listen(8080);

UPDATE

useEffect(() => {
        // getPosts();
        fetch("http://localhost:8080/feed/post")
            .then(resp => resp.json())
            .then(data => console.log('data', data));
    }, [getPosts]);

also tried this, but nothing, i receive the same error.

Expected behaviour:

I have to do a successful call to the localhost server.

Solution

As ivani suggested i just enabled the CORS, this is the code the code that I added to app.js. Not the best solution, but now i can see the response.

const allowedOrigins = ["http://localhost:3000", "http://localhost:8080"];

app.use(
    cors({
        origin: function(origin, callback) {
            if (!origin) return callback(null, true);
            if (allowedOrigins.indexOf(origin) === -1) {
                var msg =
                    "The CORS policy for this site does not " +
                    "allow access from the specified Origin.";
                return callback(new Error(msg), false);
            }
            return callback(null, true);
        }
    })
); 

Solution

As ivani suggested i just enabled the CORS.

I added this to App.js of nodeJs

const allowedOrigins = ["http://localhost:3000","http://localhost:8080"];

    app.use(
        cors({
            origin: function(origin, callback) {
                if (!origin) return callback(null, true);
                if (allowedOrigins.indexOf(origin) === -1) {
                    var msg =
                        "The CORS policy for this site does not " +
                        "allow access from the specified Origin.";
                    return callback(new Error(msg), false);
                }
                return callback(null, true);
            }
        })
    ); 

Now i can reach the data

enter image description here

this is the entire App.js file

const express = require('express');
const bodyParser = require("body-parser");
const feedRoute = require('./route/feed');
const cors = require("cors");

const app = express();

const allowedOrigins = ["http://localhost:3000", "http://localhost:8080"];

app.use(
    cors({
        origin: function(origin, callback) {
            if (!origin) return callback(null, true);
            if (allowedOrigins.indexOf(origin) === -1) {
                var msg =
                    "The CORS policy for this site does not " +
                    "allow access from the specified Origin.";
                return callback(new Error(msg), false);
            }
            return callback(null, true);
        }
    })
);

app.use(bodyParser.json()); //application json
app.use('/feed', feedRoute);
app.listen(8080);

Answered By – Legeo

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.