React:error TypeError:网络请求失败

时间:2017-07-10 16:52:39

标签: node.js react-native http-headers

我使用节点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}`)});




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

1 个答案:

答案 0 :(得分:0)

您是否更改了此类节点端代码?

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

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

首先尝试使用http://如果您在尝试使用https://

后获得了成功结果
相关问题