我一直在疯狂地努力几个小时,以使我的电子邮件正常工作。 这是网站:https://www.shafirpl.com/contact 我有一个与node.js应用程序托管在同一台服务器(数字海洋小滴)上的React应用程序。域名(shafirpl.com)具有cloudflare的SSL证书。 node.js应用程序在端口4000上运行,而react应用程序在端口80上运行。因此,现在发生的事情是react生产版本在该IP地址/服务器的端口80上运行,并且当用户单击发送按钮。当它在我的本地计算机上时,由于axios请求正在使用“ http://localhost:4000/email”而工作。但是,当我在服务器上部署并将URL更改为“ http://myServerIpAddress:4000/email”时,出现错误,提示我必须通过https发送请求。我不确定如何生成SSL证书,以便我的前端React应用可以提交axios请求,而不会出现问题。我尝试遵循certbot教程,但看来certbot需要特定的域名。所以我所做的是,使用本教程(https://dev.to/omergulen/step-by-step-node-express-ssl-certificate-run-https-server-from-scratch-in-5-steps-5b87)为我的域名(shafirpl.com)创建了密钥-证书对,并在我的server.js文件(node.js应用程序大脑)中使用了它:
const express = require("express");
// const connectDB = require("./config/db");
const path = require("path");
const https = require("https");
const fs = require("fs");
// routes variables
const emailRoute = require("./routes/email");
const resumeRoute = require("./routes/resume");
// const authRoute = require("./routes/api/auth");
const app = express();
var cors = require("cors");
// var corsOptions = {
// origin: "*",
// optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
// };
app.use(cors());
app.options("*", cors());
// Connect Database
// connectDB();
// Middleware initialization
/*
* Usually we used to install body parser and do
* app.use(bodyparser.json()). But now bodyparser comes
* packaged with express. So we just have to do express.json()
* to use bodyparser
*/
app.use(express.json({ extended: false }));
// use this when on my pc
// app.use(function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // update to match the domain you will make the request from
// res.header(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept"
// );
// next();
// });
// use this on produnction
// app.use(function (req, res, next) {
// res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
// res.header(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept"
// );
// next();
// });
// app.get("/", (req,res) => {res.send('API Running')});
// Define Routes
app.get("/", (req, res) => {
res.send("Server Running");
});
app.use("/email", emailRoute);
app.use("/resume", resumeRoute);
// app.use("/api/auth", authRoute);
// app.use("/api/profile", profileRoute);
// app.use("/api/posts", postsRoute);
// // serve static assets in production
// if (process.env.NODE_ENV === "production") {
// // set static folder
// app.use(express.static("client/build"));
// app.get("*", (req, res) => {
// res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
// });
// }
/*
* This means when the app will be deployed to heroku, it will
* look for a port specified by heroku. But since right now
* locally we don't have that, we will be running the app on
* port 5000
*/
// const PORT = process.env.PORT || 4000;
// app.listen(PORT, () => {
// console.log(`Server started on port ${PORT}`);
// });
app.listen(4000);
// comment out this line when testing on localhost
const httpsServer = https.createServer(
{
key: fs.readFileSync("/etc/letsencrypt/live/shafirpl.com/privkey.pem"),
cert: fs.readFileSync("/etc/letsencrypt/live/shafirpl.com/fullchain.pem"),
},
app
);
httpsServer.listen(443, () => {
console.log("HTTPS Server running on port 443");
});
在我的axios.post中,我正在这样使用
const url = "https://shafirpl.com:443/email";
const sendMessage = async () => {
const config = {
headers: {
'Content-Type': 'application/json',
}
}
const body = JSON.stringify({ name, email, company, message });
try {
const res = await axios.post(url, body, config);
console.log(res);
clearForm();
showSuccessMessage();
} catch (error) {
console.log(error);
showFailureMessage();
}
}
const showFailureMessage = () => {
setFailureAlert(true);
setTimeout(() => {
setFailureAlert(false)
}, 3000);
}
但是现在我再次遇到此错误: 从源“ https://shafirpl.com/email”对“ https://www.shafirpl.com”处XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:无“ Access-Control-Allow-Origin”标头存在于请求的资源上。
我实际上不知道如何解决这个问题,因为我对整个MERN堆栈构建还很陌生。谁能帮我这个?我只是想使用axios发送电子邮件
答案 0 :(得分:1)
我遇到了同样的问题-我做了什么,我从服务器和客户端上都删除了显式端口。然后我注意到我正在击中http://mydomain。...请尝试从https://mydomain访问它。
答案 1 :(得分:1)
我想我已经解决了这个问题。我决定不运行两个不同的应用程序,而是决定通过我的node.js应用程序来服务我的react build。我的方式是这样的:
const express = require("express");
// const connectDB = require("./config/db");
const path = require("path");
// routes variables
const emailRoute = require("./routes/email");
const resumeRoute = require("./routes/resume");
const app = express();
app.use(express.json({ extended: false }));
app.use("/api/email", emailRoute);
app.use("/api/resume", resumeRoute);
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(80);
然后在我的axios请求上我做到了:
const url = "/api/email"; const sendMessage = async () => {
const config = {
headers: {
'Content-Type': 'application/json',
}
}
const body = JSON.stringify({ name, email, company, message });
try {
const res = await axios.post(url, body, config);
console.log(res);
clearForm();
showSuccessMessage();
} catch (error) {
console.log(error);
showFailureMessage();
}
}
现在一切正常。 对于发送文件下载的简历,我不必使用/ api / resume 像这样的东西
<Nav.Link eventKey="6" activeClassName="active-nav" href="https://shafirpl.com/api/resume" target="_blank" rel="noopener noreferrer">Resume</Nav.Link>
现在,简历下载也可以正常工作 感谢您的所有帮助