HTTPS发行节点服务器MERN堆栈

问题描述 投票:0回答:1

我一直在疯狂地努力几个小时,以使电子邮件正常运行。这是网站: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发送电子邮件

我一直在疯狂地努力几个小时,以使电子邮件正常运行。这是网站:https://www.shafirpl.com/contact我有一个与应用程序托管在与节点相同的服务器(数字海洋小滴)上的react应用....

node.js reactjs mern
1个回答
0
投票

我有同样的问题-我做了什么,我从服务器和客户端上都删除了显式端口。然后我注意到我正在击中http://mydomain。...请尝试从https://mydomain中访问它。

© www.soinside.com 2019 - 2024. All rights reserved.