У меня есть приложение React с Express Server. Я получаю несколько ошибок, они выглядят примерно так ..
xhr.js:178 POST http://localhost:3000/contactus 404 (Not Found)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
handleSubmit @ Contact.js:20
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchDiscreteEvent @ react-dom.development.js:4168
Contact.js:24 Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:61)
Server. js Express Server / Back-end
require("dotenv").config();
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
var API_KEY = process.env.MAILGUN_API_KEY;
var DOMAIN = process.env.MAILGUN_DOMAIN;
var mailgun = require("mailgun-js")({ apiKey: API_KEY, domain: DOMAIN });
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// app.use(express.static(__dirname + "/public"));
// Define API routes here
app.post("/contactus", function (req, res) {
console.log(req.body);
const data = {
from: req.body.email,
to: "<__RECEIVER__>",
subject: "Contact",
html: `hi`,
};
mailgun.messages().send(data, (error, body) => {
if (error) {
throw error;
} else {
console.log(body);
res.json({ message: "success" });
}
});
});
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`? ==> API server now on port ${PORT}!`);
});
Я просмотрел промежуточное программное обеспечение и подумал, что это возможно. Затем я просмотрел и проверил Front-end / Contact. js, чтобы убедиться, что он настроен правильно. Кажется, все работает нормально, единственная проблема - ошибка сервера POST-маршрута. Я также, хотя что-то может быть не так с заголовками, но я не получаю ошибку политики CORS. Может, я что-то упустил ..
Контакт. js Приложение React / Front-end
import React, { useState } from "react";
import axios from "axios";
import styles from "./Contact.module.css";
import RoomIcon from "@material-ui/icons/Room";
import PhoneIcon from "@material-ui/icons/Phone";
import EmailIcon from "@material-ui/icons/Email";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
function Contact() {
const [sentMessage, setSentMessage] = useState("");
const [description, setDescription] = useState("");
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const data = { name, email, description };
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
try {
axios
.post("/contactus", data)
.then((res) => {
console.log(res);
})
.catch((err) => console.log(err));
} catch (e) {
console.log(e);
}
};
return (
<div>
<div className={styles["ContactBackgroundPicture"]}>
<h1 className={styles["ContactHeader"]}>Contact Us</h1>
</div>
<div className={styles["ContactWrapper"]}>
<div className={styles["Contact"]}>
<div className={styles["AddressWrapper"]}>
<div className={styles["ContactUsHeader"]}>
<RoomIcon style={{ color: "green", marginBottom: "2%" }} />
<h5>Address</h5>
<br />
<hr />
<p>17102 Sentinel Ln. Lindale Tx. 75771</p>
</div>
</div>
<div className={styles["PhoneWrapper"]}>
<div className={styles["ContactUsHeader"]}>
<PhoneIcon style={{ color: "green", marginBottom: "2%" }} />
<h5>Phone</h5>
<br />
<hr />
<p>903-705-8338</p>
</div>
</div>
<div className={styles["EmailWrapper"]}>
<div className={styles["ContactUsHeader"]}>
<EmailIcon style={{ color: "green", marginBottom: "2%" }} />
<h5>Email</h5>
<br />
<hr />
<p>txjuventusfc@gmail.com</p>
</div>
</div>
</div>
<div className={styles["ContactOr"]}>OR</div>
<div className={styles["ContactSubmitMessage"]}>
{!sentMessage.length ? null : "Message Successfully Sent!"}
</div>
<div className={styles["FormWrapper"]}>
<h3 className={styles["FormHeader"]}>Message Us</h3>
<form onSubmit={handleSubmit} className={styles["TextFieldWrapper"]}>
<div className={styles["TopTextField"]}>
<div className={styles["TopFormField"]}>
<TextField
onChange={(e) => setName(e.target.value)}
fullWidth
required
id="standard-basic"
label="Enter Your Name"
name="name"
/>
</div>
<div className={styles["BottomFormField"]}>
<TextField
onChange={(e) => setEmail(e.target.value)}
fullWidth
required
id="standard-basic"
label="Enter Your Email Address"
name="email"
/>
</div>
</div>
<div className={styles["BottomTextField"]}>
<TextField
onChange={(e) => setDescription(e.target.value)}
fullWidth
required
id="standard-basic"
label="Your Message Here..."
name="description"
/>
</div>
<Button
type="submit"
className={styles["SubmitButton"]}
variant="contained"
color="secondary"
>
Submit
</Button>
</form>
</div>
</div>
</div>
);
}
export default Contact;