I have a React app and within this app a folder called backend. This folder contains 2 files:
Config contains a variable with email and password through nodemailer. Index.js (which is what my server is supposed to run) has this:
const path = require("path");
const express = require("express");
const transporter = require("./config");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const buildPath = path.join(__dirname, "..", "build");
app.use(express.json());
app.use(express.static(buildPath));
app.post("/send", (req, res) => {
try {
const mailOptions = {
from: req.body.email, // sender address
to: process.env.email, // list of receivers
subject: req.body.subject, // Subject line
html: `
<p>You have a new contact request.</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
<li>Subject: ${req.body.subject}</li>
<li>Message: ${req.body.message}</li>
</ul>
`,
};
transporter.sendMail(mailOptions, function (err, info) {
if (err) {
res.status(500).send({
success: false,
message: "Something went wrong. Try again later",
});
} else {
res.send({
success: true,
message: "Thanks for contacting us. We will get back to you shortly",
});
}
});
} catch (error) {
res.status(500).send({
success: false,
message: "Something went wrong. Try again later",
});
}
});
app.listen(3030, () => {
console.log("server start on port 3030");
});
Then, within a different folder (components) I have a component file that takes the form information and it's supposed to take it to the server:
import React, { useState } from "react";
import axios from "axios";
import { Form, Button } from "react-bootstrap";
import Navbar from "../components/Navbar";
import BottomNav from "../components/BottomNav";
const Contact = () => {
const [state, setState] = useState({
name: "",
email: "",
subject: "",
message: "",
});
const [result, setResult] = useState(null);
const sendEmail = event => {
event.preventDefault();
axios
.post("/send", { ...state })
.then(response => {
setResult(response.data);
setState({
name: "",
email: "",
subject: "",
message: "",
});
})
.catch(() => {
setResult({
success: false,
message: "Something went wrong. Try again later",
});
});
};
const onInputChange = event => {
const { name, value } = event.target;
setState({
...state,
[name]: value,
});
};
return (
<div>
<Navbar />
{result && (
<p className={`${result.success ? "success" : "error"}`}>
{result.message}
</p>
)}
<form
className="phs-form-wrapper mt-8 h-screen flex flex-col items-center "
onSubmit={sendEmail}
>
<Form.Group
className=" phs-form-group flex flex-col items-center"
controlId="name"
>
<Form.Label className="phs-form-label mr-2">Full Name</Form.Label>
<Form.Control
type="text"
name="name"
value={state.name}
onChange={onInputChange}
/>
</Form.Group>
<Form.Group
className=" phs-form-group flex flex-col items-center"
controlId="email"
>
<Form.Label className="phs-form-label mr-2">Email</Form.Label>
<Form.Control
type="text"
name="email"
value={state.email}
onChange={onInputChange}
/>
</Form.Group>
<Form.Group
className=" phs-form-group flex flex-col items-center"
controlId="subject"
>
<Form.Label className="phs-form-label mr-2">Subject</Form.Label>
<Form.Control
type="text"
name="subject"
value={state.subject}
onChange={onInputChange}
/>
</Form.Group>
<Form.Group
className=" phs-form-group flex flex-col items-center"
controlId="subject"
>
<Form.Label className="phs-form-label mr-2">Message</Form.Label>
<Form.Control
as="textarea"
name="message"
value={state.message}
rows="3"
onChange={onInputChange}
/>
</Form.Group>
<Button
className="phs-form-submit-button bg-black text-white p-4 mt-4"
variant="primary"
type="submit"
>
Submit
</Button>
</form>
<BottomNav />
</div>
);
};
export default Contact;
I am getting an error on both servers. On localhost:3000 which is where I run my react app whenever I try to submit the info I get a:
VM635:1 POST http://localhost:3000/send 404 (Not Found)
On localhost:3030:
GET http://localhost:3030/ 404 (Not Found)
localhost/:1 Refused to load the image 'http://localhost:3030/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
I note that my axios has a .post("/send") but I tried to change this to localhost:3030/send and doesn't work either.
Additionally I have 2 package.json files, one within my react folder (web) and another one within my backend folder.
The backend one has a script like this:
"scripts": {
"dev": "nodemon src/index.js"
}
The web one has a different script so I run a different server:
"scripts": {
"start": "npm run watch:css && react-scripts start",
"build": "npm run watch:css && react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"watch:css": "postcss src/assets/tailwind.css -o src/assets/main.css"
}
Any ideas?
When you're running both the backend and frontend servers on different ports (:3000 and :3030 in this case), you need to particularly mention the whole url in axios call. In this case, /send
is considered as http://localhost:3000
where the POST method doesn't exists (The reason why you're getting 404). You must make the following axios call:
const sendEmail = event => {
event.preventDefault();
axios
.post("http://localhost:3030/send", state, {
headers: {
'Access-Control-Allow-Origin' : '*'
},
})
.then(response => {
...
})
.catch(() => {
...
});
};
Also you don't need to spread the state in axios call. The reason is axios call accepts second argument as object.
On your react app try sending it to "http://localhost:3030/send" instead "/send". I believe its because your server URL and your react dev server URL are different when you run it locally
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.