Node.js 无法从本地主机获取数据
我用NodeJs制作了我的第一个API 如果我尝试从浏览器的url访问资源,就会得到这个结果 我成功地与邮递员取得了联系。 现在,我试图用一个图形站点设置一个小调用,但无法获取数据 这是我在一个传奇故事中试过的电话Node.js 无法从本地主机获取数据,node.js,reactjs,api,fetch,Node.js,Reactjs,Api,Fetch,我用NodeJs制作了我的第一个API 如果我尝试从浏览器的url访问资源,就会得到这个结果 我成功地与邮递员取得了联系。 现在,我试图用一个图形站点设置一个小调用,但无法获取数据 这是我在一个传奇故事中试过的电话 export const fetchWrapper = async url => { var request = new Request({ url: url, method: "GET" }); await fetch(request)
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);
}
}
这些是我在控制台中遇到的错误
更新
useEffect(() => {
// getPosts();
fetch("http://localhost:8080/feed/post")
.then(resp => resp.json())
.then(data => console.log('data', data));
}, [getPosts]);
正如注释中所建议的,这是我的节点代码
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]);
我也试过了,但是没有,我收到了同样的错误
预期行为:
useEffect(() => {
// getPosts();
fetch("http://localhost:8080/feed/post")
.then(resp => resp.json())
.then(data => console.log('data', data));
}, [getPosts]);
我必须成功地调用localhost服务器
解决方案
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);
}
})
);
尝试将代理字段添加到React文件夹中的
package.json
:
“代理”:http://localhost:8080"
然后,提出如下请求:
//这也将避免CORS问题
常量url=`/feed/posts`;
请求示例:
//创建一个状态“Array”(或对象)来保存您的所有帖子
const[posts,setPosts]=useState([])
useffect(()=>{
const getPosts=async()=>{
试一试{
const response=wait fetch('/feed/post');
const data=wait response.json();
设置柱(数据)
}捕捉(错误){
console.log(err);//获取失败
}
}
//提出请求
getPosts()
},[/*无依赖项*/])
返回(
//JSX在这里使用“posts”
)
正如伊凡尼建议的那样,我刚刚启用了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);
您应该尝试在不使用生成器函数(
function*
/yield
)和不使用async wait
)的情况下成功调用该端点-当这起作用时,添加使您的程序运行良好的语言功能。感谢您的评论,我尝试插入一个简单的fetch()。然后()和URL,但是我也犯了同样的错误,你认为如果我创建一个临时github repo并将其放到网上,这样每个人都可以看到我的所有代码,会更好吗?或者我不知道…邮递员屏幕截图可以帮助你吗?你是否已经按照描述启用了CORS标题?从屏幕截图上可以看出,您正在访问端口8080处的端点,而应用程序从端口3000提供服务,这将被视为另一个来源。Postman并不关心这一点,但javascript发出的请求确实如此。@Legeo您看到的错误是什么?不清楚为什么post
请求是红色的-您突出显示并显示request
和response
标题的请求不是post
请求。@goto1我更改了第二个图像,但正如您所看到的,响应错误总是一样的:|只是一个注释,请添加环境变量以检查部署类型,如果其值为“Dev”,则只能添加此检查。您也可以尝试添加与CORS相关的npm模块-