gpt4 book ai didi

node.js - React - 仅在 HTTPS 上发送 POST 请求时出现网络错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:25 24 4
gpt4 key购买 nike

我有一个 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? .无论如何,这只是一个类(class)项目,来回只有无意义的字符串。

最佳答案

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

你试过用过吗

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

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

关于node.js - React - 仅在 HTTPS 上发送 POST 请求时出现网络错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50518794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com