NodeJ로 첫 번째 API를 만들었습니다.
이것은 브라우저의 URL에서 리소스에 액세스하려고하면 얻는 것입니다.
나는 우편 배달부와 함께 게시물에 액세스하는 데 성공했습니다. 이제 그래픽 사이트에 약간의 전화를 걸려 고했지만 데이터를 가져올 수 없었습니다.
이것은 내가 사가에서 시도한 전화입니다
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;
}
);
};
그리고 이것은 사가입니다
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);
}
}
그리고 이것은 내가 콘솔에있는 오류입니다.
최신 정보
주석에서 제안했듯이 이것은 내 노드 코드입니다.
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);
최신 정보
useEffect(() => {
// getPosts();
fetch("http://localhost:8080/feed/post")
.then(resp => resp.json())
.then(data => console.log('data', data));
}, [getPosts]);
또한 이것을 시도했지만 아무것도 없었으며 동일한 오류가 발생합니다.
예상되는 동작 :
localhost 서버에 대한 성공적인 호출을해야합니다.
해결책
ivani가 방금 CORS를 활성화했다고 제안했듯이 이것은 app.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);
}
})
);
ivani가 제안했듯이 CORS를 활성화했습니다.
나는 이것을 nodeJs의 App.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);
}
})
);
이제 데이터에 도달 할 수 있습니다.
이것은 전체 App.js 파일입니다.
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);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다