繁体   English   中英

反应:错误TypeError:网络请求失败

[英]React : error TypeError: Network request failed

我已经将节点js用作仅响应一些Json数据的服务器。

 //https var privateKey = fs.readFileSync('./ssl/key.pem').toString(); var certificate = fs.readFileSync('./ssl/cert.pem').toString(); var credentials = {key: privateKey, cert: certificate}; var httpServer = http.createServer(app); var httpsServer = https.createServer(credentials, app); var PORT = 18080; var SSLPORT = 18081; httpServer.listen(PORT, function () { console.log('HTTP Server is running on: http://localhost:%s', PORT); }); httpsServer.listen(SSLPORT, function () { console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT); }); app.get('/listUsers', function (req, res) { res.header('Content-Type', 'application/json'); res.header('Access-Control-Allow-Origin','*'); res.send(JSON.stringify({ a: 1 ,'id':2,'title':3})) }); 

我的反应代码如下:

 let http_url = "https://localhost:18081/listUsers"; fetch(http_url, init) .then((response) => response.json()) .then((responseJson) => { this.setState({message: `${responseJson['id']} - ${responseJson['title']}`}); }) .catch(e => {console.log(`error ${e}`)}); 

通过在Chrome中输入“ https:// localhost:18081 / listUsers ”,我可以获得真正的json响应结果,但是反应模拟器总是告诉我“反应:错误TypeError:网络请求失败”。 我认为原因可能是节点响应标头不正确。 谁能给我一些建议? 非常感谢!

您是否更改过这样的节点端代码?

res.json({ a: 1 ,'id':2,'title':3});

我认为您正在将数据作为字符串传递。 要求是json

另外,如果获得成功,请先尝试使用http://,然后再尝试使用https://。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM