[英]Why can I not access my node.js basic public API?
Whenever I try to accesse http://localhost:3000/api/courses it doesn't load at all, just hangs.每当我尝试访问http://localhost:3000/api/courses时,它根本不会加载,只是挂起。 I've had a similar problem with React routing not loading any subpages.我在 React 路由没有加载任何子页面时遇到了类似的问题。 I'm not sure what could be the reason.我不确定可能是什么原因。 I am connected via mobile hotspot but I do not connect to the internet using a proxy.我通过移动热点连接,但我没有使用代理连接到互联网。
I've tried different ports with the same result.我尝试了不同的端口,结果相同。
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.write('Hello World');
res.end();
}
if (req.url === '/api/courses') {
res.write(JSON.stringify([1, 2, 3]));
res.end();
}
});
server.listen(3000);
console.log('Listening on port 3000...');
Expected result is to show me the array [1, 2, 3]
.预期的结果是向我展示数组[1, 2, 3]
。 Actual result is that the page just hangs without loading.实际结果是页面只是挂起而没有加载。
No Changes, It is working fine in my pc, Try once in an incognito window or change port.没有更改,它在我的电脑上运行良好,在隐身 window 中尝试一次或更改端口。
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.write("Hello World");
res.end();
}
if (req.url === "/api/courses") {
res.write(JSON.stringify([1, 2, 3]));
res.end();
}
});
server.listen(8080);
console.log("Listening on port 8080...")
Check link - https://i.stack.imgur.com/R6mLQ.png检查链接 - https://i.stack.imgur.com/R6mLQ.png
Because you are not returning the valid JSON object.因为您没有返回有效的 JSON object。
res.write(JSON.stringify([1, 2, 3]));
Try something like this尝试这样的事情
res.write(JSON.stringify({"result":[1, 2, 3])});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.