【问题标题】:React - Network Error when sending POST request only when on HTTPSReact - 仅在 HTTPS 上发送 POST 请求时出现网络错误
【发布时间】:2018-05-24 22:01:31
【问题描述】:

我有一个 Web 应用程序,其中前端使用 React (create-react-app) 完成,并且部署在 Heroku 上。后端使用 node.js/express 完成,它在 Amazon EC2 上运行。 当我在 localhost 或 Heroku 上部署前端时,如果我使用 HTTP 作为http://myapp.heroku.com 访问它,让应用程序运行没有任何问题。当我使用 HTTPS(这是 Heroku 上的默认设置)作为https://myapp.heroku.com 访问它时,就会出现问题。当我这样做并向 Amazon EC2 上的 node.js 服务器发送请求时,我收到以下错误:

Error: Network Error
Stack trace:
createError@https://myapp.herokuapp.com/static/js/bundle.js:1555:15
handleError@https://myapp.herokuapp.com/static/js/bundle.js:1091:14

这是前端向 node.js 服务器发送请求的部分:

_deflateAscii(valueAscii){
axios.post('//My-EC2-Instance-Here.compute.amazonaws.com:80/deflate/ascii', {inflatedAscii: valueAscii}).then(res => {
  this.setState(
    {
      inflatedAscii: valueAscii,
      inflatedHex: res.data.inflatedHex,
      deflatedBase64: res.data.deflatedBase64,
      deflatedHex: res.data.deflatedHex
    },
    this._setTextBoxesValues
  );
}).catch((err) => {
   console.log(err)});
  }

这是我在服务器端使用的模块:

const express = require('express');
const cors = require('cors');
const http = require('http');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());

以及处理来自前端的请求的部分:

app.post('/deflate/ascii', function(req, res){
try{
  console.log('request received');
  var inflatedHexValue = convert.asciiToHex(req.body.inflatedAscii);
  var deflatedBase64Value = deflate.asciiToBase64(req.body.inflatedAscii);
  var deflatedHexValue = deflate.asciiToHex(req.body.inflatedAscii);
}catch(err){
  console.log(err);
  res.status(500).send(err);
}
response = {
  deflatedBase64: deflatedBase64Value,
  deflatedHex: deflatedHexValue,
  inflatedHex: inflatedHexValue
};
res.end(JSON.stringify(response));
console.log('response sent');
});

当我在前端收到网络错误时,node.js 服务器没有收到请求,但我已经使用 Wireshark 进行了一些诊断,并与 EC2 服务器握手,但流量没有任何 HTTP 流量:

TCP-traffic between https://myapp.heroku.com/ and My-EC2-Instance-Here.compute.amazonaws.com

如果前端是 HTTPS,我是否需要在后端使用 SSL?从这篇文章中我了解到,它也可以不用Do we need ssl certificate for both front end and backend?。无论如何,这只是一个课程项目,只有无意义的字符串来回切换。

【问题讨论】:

    标签: node.js reactjs ssl heroku https


    【解决方案1】:

    当您在浏览器中通过 https 访问您的网站时,您需要禁用对混合内容(http 和 https)的阻止。因此,您的浏览器将连接归类为不安全。 所以是的,在后端和前端都使用 SSL/TSL 会很好。

    你有没有尝试使用

    res.json(response);
    res.status(200).end();

    或将标头设置为 application/json? 我建议将您的 res 调用放入 try catch 块中,因为您的 res.end 无论如何都会被执行。

    【讨论】:

      猜你喜欢
      • 2020-10-26
      • 2021-12-21
      • 2018-08-03
      • 2016-11-05
      • 2018-06-18
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多