json-server
是一个用于快速创建 RESTful API 的工具,它基于 Node.js 和 Express。当你遇到来自浏览器的 GET 请求问题时,可能是由于以下几个原因:
可以通过设置 CORS(跨源资源共享)来解决。在 json-server 的配置文件 db.json
中添加以下内容:
{
"posts": [...],
"comments": [...],
"profile": {...},
"cors": true
}
或者在启动 json-server 时使用命令行参数:
json-server --watch db.json --cors
确保你的 GET 请求 URL 是正确的。例如,如果你有一个资源 posts
,你应该这样请求:
GET http://localhost:3000/posts
如果需要特定 ID 的资源,URL 应该包含 ID:
GET http://localhost:3000/posts/1
确保 json-server 已经启动并且运行在正确的端口上。启动命令通常是:
json-server --watch db.json
默认情况下,它会运行在 http://localhost:3000
。
检查你的 db.json
文件,确保请求的资源确实存在。例如,如果你请求 /posts
,确保 db.json
中有 posts
数组。
假设你的 db.json
文件如下:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
你可以使用以下 JavaScript 代码通过 Fetch API 发送 GET 请求:
fetch('http://localhost:3000/posts')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
通过以上方法,你应该能够解决大多数来自浏览器的 GET 请求问题。如果问题依然存在,建议检查浏览器的开发者工具中的网络请求详情,查看具体的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云