Node.js HTTPS问题节点服务器MERN堆栈

Node.js HTTPS问题节点服务器MERN堆栈,node.js,reactjs,mern,Node.js,Reactjs,Mern,为了让我的电子邮件正常工作,我已经疯狂地试了几个小时。 这是网站: 我有一个react应用程序和node.js应用程序托管在同一台服务器上(一个数字海洋水滴)。域名(shafirpl.com)具有来自cloudflare的SSL证书。node.js应用程序在端口4000上运行,而react应用程序在端口80上运行。因此,现在发生的是react生产构建正在该IP地址/服务器的端口80上运行,当用户单击send按钮时,我有一个axios post请求。当它在我的本地机器上运行时,axios请求正在使

为了让我的电子邮件正常工作,我已经疯狂地试了几个小时。 这是网站: 我有一个react应用程序和node.js应用程序托管在同一台服务器上(一个数字海洋水滴)。域名(shafirpl.com)具有来自cloudflare的SSL证书。node.js应用程序在端口4000上运行,而react应用程序在端口80上运行。因此,现在发生的是react生产构建正在该IP地址/服务器的端口80上运行,当用户单击send按钮时,我有一个axios post请求。当它在我的本地机器上运行时,axios请求正在使用“”。但是当我在服务器上部署并将URL更改为“”时,我得到一个错误,即我必须通过https发送请求。我不知道如何生成SSL证书,以便我的前端react应用程序可以提交axios请求,而不会出现问题。我试着学习certbot教程,但似乎certbot需要一个特定的域名。因此,我所做的是,我使用本教程()为我的域名(shafirpl.com)创建了密钥证书对,并在我的server.js文件(node.js app brain)中使用如下内容:

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);
}
<Nav.Link eventKey="6" activeClassName="active-nav" href="https://shafirpl.com/api/resume" target="_blank" rel="noopener noreferrer">Resume</Nav.Link>
但现在我又犯了一个错误: CORS策略已阻止从源“”访问“”处的XMLHttpRequest:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源”标头


我实际上不知道如何解决这个问题,因为我对整个MERN堆栈构建还很陌生。有人能帮我吗?我只是想用axios发送电子邮件,我也遇到了同样的问题——我所做的是,从服务器和客户端删除了显式端口。然后我注意到我在打。。。。请尝试从…访问它。。。这对我来说是个好办法:)希望能有帮助

我也遇到了同样的问题-我所做的是从服务器和客户端删除显式端口。然后我注意到我在打。。。。请尝试从…访问它。。。这对我来说是个好办法:)希望能有帮助

我想我解决了这个问题。我决定通过node.js应用程序为我的react构建提供服务,而不是运行两个不同的应用程序。我是这样做的:

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 像这样的

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);
}
<Nav.Link eventKey="6" activeClassName="active-nav" href="https://shafirpl.com/api/resume" target="_blank" rel="noopener noreferrer">Resume</Nav.Link>
继续
现在下载的简历也很好
谢谢你的帮助

我想我已经解决了这个问题。我决定通过node.js应用程序为我的react构建提供服务,而不是运行两个不同的应用程序。我是这样做的:

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 像这样的

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);
}
<Nav.Link eventKey="6" activeClassName="active-nav" href="https://shafirpl.com/api/resume" target="_blank" rel="noopener noreferrer">Resume</Nav.Link>
继续
现在下载的简历也很好
感谢所有帮助

同时请取消注释:
//const-PORT=process.env.PORT | | 4000部分--在部署时,始终是一个很好的做法,因为Heroku/无论您使用什么环境来部署,服务器都会分配自己的端口!另外,请取消注释:
//const-PORT=process.env.PORT | 4000部分--在部署时,始终是一个很好的做法,因为Heroku/无论您使用什么环境来部署,服务器都会分配自己的端口!Shafi,在Axios API调用中,如何指定主机名?喜欢http://.../api/login 你是怎么指定的?我的前端和后端都在不同的目录下。在Axios API调用中,您是如何指定主机名的?喜欢http://.../api/login 你是怎么指定的?我的前端和后端都在不同的目录中