Я сделал свой первый API с NodeJs
, вот что я получу, если попытаюсь получить доступ к ресурсу с URL браузера
Мне удалось получить доступ к сообщениям почтальона. Теперь я попытался установить небольшой вызов с графическим c сайтом, но мне не удалось получить данные
. Это вызов, который я пытался выполнить в саге
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;
}
);
};
* 1014. * а это сага
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);
}
}
и это ошибки, которые у меня есть в консоли
ОБНОВЛЕНИЕ
Как указано в комментарии, это мой код узла
контроллер / канал . 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
}
});
};
маршрут / подача. 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;
приложение. 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);
ОБНОВЛЕНИЕ
useEffect(() => {
// getPosts();
fetch("http://localhost:8080/feed/post")
.then(resp => resp.json())
.then(data => console.log('data', data));
}, [getPosts]);
тоже пробовал это, но ничего, я получаю ту же ошибку.
Ожидаемое поведение:
Я должен сделать успешный звонок на сервер localhost.
Решение
Как иван предложил, я только что включил CORS, это код, который я добавил в приложение. js. Не лучшее решение, но теперь я вижу ответ.
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);
}
})
);