[英]How can a http.createServer receive data from needle.post using fs.createReadStream
[英]How to access data from the createServer() method
我有一个模拟服务器,它提供一些 json 数据。 服务器工作正常,但如何通过 fetch/axios 访问数据? 我正在使用 fetch 从端点 http://localhost:6000/users 获取。
const http = require('http');
const json = require('./users.json');
const port = 6000;
http.createServer((req, res) => {
if (req.url === '/users') {
// Test error
res.write(JSON.stringify(json)).end();
} else {
res.writeHead(404).end();
}
}).listen(port, () => console.log(`Mock server listening on port ${port}`))
const { data: usersData } = useFetch("http://localhost:6000/users")
这是钩子
const [data, setData] = useState(null);
useEffect(() => {
const _fetch = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (err) {
console.log(err)
}
};
_fetch();
}, [url]);
return {
data,
};
};
export default useFetch;
我在本地收到以下错误消息。
GET http://localhost:6000/users net::ERR_EMPTY_RESPONSE
useFetch.js?7d5b:38 TypeError: Failed to fetch
at _callee$ (useFetch.js?7d5b:22:1)
at tryCatch (runtime.js?96cf:63:1)
at Generator.invoke [as _invoke] (runtime.js?96cf:294:1)
at Generator.eval [as next] (runtime.js?96cf:119:1)
at asyncGeneratorStep (asyncToGenerator.js?dbc6:3:1)
at _next (asyncToGenerator.js?dbc6:25:1)
at eval (asyncToGenerator.js?dbc6:32:1)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js?dbc6:21:1)
at _fetch (useFetch.js?7d5b:49:1)
```
const port = 6000;
useFetch("http://localhost:5500/users")
您正在使用两个不同的端口号,您应该更改其中一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.