你能看看我的代码吗?我可以在 localhost:5000 (node+react) 上创建一个应用程序,但是当我在 Heroku 中部署它时,我无法从 POST 请求中获得响应。它给我的只是405错误。我已经修复了 2 天,但没有得到任何解决方案。如果您能帮助我,我们将不胜感激。
这是来自 Web 控制台的错误消息: Uncaught (in promise) Error: Request failed with status code 405
这是我的 github repo 链接,用于查看我的代码:github.com/sajpanchal/portfolio
这是我关于me.js的反应代码:
handleSubmit = (event) => {
const data = { ...this.state.data };
event.preventDefault();
axios.post(`${BASE_API_URL}/api/email`, data).then((res) => {
console.log(res);
console.log(res.data);
});
};
这是我的 node.js 文件 index.js:
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const logger = require("morgan");
const app = express();
var nodemailer = require("nodemailer");
require("dotenv").config();
const { USER_PASSWORD, USER_EMAIL, RECEIVER_EMAIL } = process.env;
console.log(USER_PASSWORD);
//React build app setup
app.use(express.static(path.join(__dirname, "build"))); // serve all static files from build
app.use(logger("dev"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "build", "index.html")); // this will keep our client side routing functional.
});
app.use(bodyParser.json());
// // allows your app to interact with the apps running on different servers.
//this will set the htstp server response header.
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Acess-Control-Allow-Headers", "Content-Type , Authorization");
next();
});
//get request
app.get("/api", (req, res, next) => {
res.send("API status: OK");
});
var transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: USER_EMAIL,
pass: USER_PASSWORD,
},
});
app.post("/api/email", (req, res, next) => {
var mailOptions = {
from: req.body.email,
to: RECEIVER_EMAIL,
subject: req.body.subject,
html: `<strong>sender: ${req.body.email}</strong><br>Message: <strong>${req.body.message}</strong>`,
};
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
res.status(400).json({
error: error,
});
} else {
res.status(200).json({
success: true,
});
}
});
});
const port = process.env.PORT || 5000;
app.listen(port, "0.0.0.0");
console.log("connected to port: ", port);
完整的项目可在 github 上找到:https ://github.com/sajpanchal/portfolio
请注意,我已将 nodejs 项目添加到我的 react 项目根文件夹中,然后我为 node 项目创建了 react 的构建版本。