我使用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);
}
}
这些是我在控制台中出现的错误
UPDATE
如评论所建议,这是我的节点代码
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]);
也尝试过此操作,但是什么也没有,我收到相同的错误。
预期行为:
我必须成功调用本地主机服务器。
解决方案
正如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);
}
})
);
答案 0 :(得分:3)
正如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);
答案 1 :(得分:0)
尝试在 React 文件夹中的package.json
中添加代理字段:
"proxy": "http://localhost:8080"
然后,像这样发出您的请求:
// this will also avoids CORS issues
const url = `/feed/posts`;
请求示例:
// Create a state `Array` (or Object) that will hold all your posts
const [posts, setPosts] = useState([])
useEffect(() => {
const getPosts = async () => {
try {
const response = await fetch('/feed/post');
const data = await response.json();
setPosts(data)
} catch(err) {
console.log(err); // failed to fetch
}
}
// Make the request
getPosts()
}, [/* no dependencies */])
return (
// JSX use 'posts' here
)