I have problem with the server when deploy my app with gh-pages. When i try to POST on /contact url it respond 405 Method Not Allowed.
I tried with cors on express but it's same. My client side is with React.
When I run it on localhost everything work normal but in production like server doesn't exist. Should I add something in my react app to connect them or...?
const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');
const path = require('path')
const nodemailer = require('nodemailer');
const cors = require('cors')
const pass = require('./.vscode/settings.json')
const config = require('./config')
var allowedOrigins = ['http://localhost:3000','https://some.github.io'];
const corsOptions = {
origin: function(origin, callback){
if(!origin) return callback(null, true);
if(allowedOrigins.indexOf(origin) === -1){
var msg = 'The CORS policy for this site does not ' +
'allow access from the specified Origin.';
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true,
}
const app = express();
const route = express.Router();
app.use(express.static(path.join(__dirname, 'client' ,'/public')))
app.use(cors(corsOptions))
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'https://some.github.io');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', route)
http.createServer(app).listen(config.port, () => {
console.log(`Listening on port ${config.port}`)
});
app.get('/', (req, res) => {
console.log('server')
res.sendFile(path.join(__dirname, 'client' ,'/public', 'index.html'));
});
const transporter = nodemailer.createTransport({
port: 465,
host: "smtp.gmail.com",
auth: {
user: 'email',
pass: pass,
},
secure: true,
});
route.get('/contact', (req,res) => {
res.status(200).send('Contact page')
})
route.post('/contact', (req, res) => {
const {name, email, message} = req.body
console.log(req.body)
const mailToMe = {
from: 'email', // sender address
to: 'email', // list of receivers
subject: name,
text: message,
html: message + `<br> From: ${email}`,
};
transporter.sendMail(mailToMe, (error, info) => {
if(error) {
return console.log(error)
}
res.redirect('/contact')
res.status(200)
});
})
That is the client side component in react:
const ContactForm = () => {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [message, setMessage] = useState('')
const [errorName, setErrorName] = useState('')
const [errorEmail, setErrorEmail] = useState('')
const [errorMessage, setErrorMessage] = useState('')
const [isSubmited, setIsSubmited] = useState(false)
useEffect(() => {
if(isSubmited){
setTimeout(() => {
setIsSubmited(false)
}, 7000)
}
})
const handelValidation = () => {
setErrorName('')
setErrorEmail('')
setErrorMessage('')
// Name
if (!name) {
setErrorName("Name field cannot be empty!")
return false
}
if (!name.match(/[A-Z][a-z]+ [A-Z][a-z]+/)) {
setErrorName("Тhe first and second names must begin with a capital letter and continue with lowercase letters!")
return false
}
// Email
if (email === '') {
setErrorEmail("Email field cannot be empty!")
return false
}
if (!email.match(/[A-Za-z0-9.]+#[a-z]+.[a-z]+.?[a-z]+/)) {
setErrorEmail("Email must be valid!")
return false
}
// Message
if (message === '') {
setErrorMessage("Message field cannot be empty!")
return false
}
if(message.length <= 10) {
setErrorMessage("Message should more the 10 characters!")
return false
}
return true
}
const handleSubmit = (e) => {
e.preventDefault()
let result = handelValidation();
console.log(name, email, message)
if (!result) {
return
}
let data = { name: name, email: email, message: message }
axios.post(`/contact`, data).catch(e => console.log(e))
setName('')
setEmail('')
setMessage('')
setIsSubmited(true)
}
return (
<Form onSubmit={handleSubmit}>
<Input
onChange={e => setName(e.target.value)}
label={"What is your name?"}
name={"name"}
icon={"far fa-user"}
placeholder={"Type your first and second name..."}
value={name}
isError={errorName}
/>
{errorName ? <Notification error={errorName} /> : ""}
<Input
onChange={e => setEmail(e.target.value)}
label={"Write your email"}
name={"email"}
icon={"far fa-envelope"}
placeholder={"Type your email..."}
value={email}
isError={errorEmail}
/>
{errorEmail ? <Notification error={errorEmail} /> : ""}
<Input
onChange={e => setMessage(e.target.value)}
label={"What is your message to me?"}
name={"message"}
icon={"far fa-comment-alt"}
placeholder={"Type your message..."}
value={message}
isError={errorMessage}
/>
{errorMessage ? <Notification error={errorMessage} /> : ""}
<SubmitButton title={"Submit form"} />
{isSubmited ? <Div>Thank you for contacting me! You must have received an automatic reply
to the email you entered above.</Div> : ""}
</Form>
)
}
Github Pages does not support any kind of server-side programming.
You need hosting (there are many cloud services that will let you deploy a Node.js web service to them as well as VPSs and dedicated servers you can rent) on which you can run your server-side JavaScript. You can't just drop it onto Github pages and have it do anything.
You need to deploy public server instead of local server. Local servers are accessible for only you, not the others.
Related
I am working with this NodeJS project using express-session to create session for my application. The problem is, when I make a post request to the http://localhost:5500/login, a session is created with additional property userid that I added intentionally. Then, when I use Postman to make a get request to http://localhost:5500/, the application actually receives the session with the property userid and redirect the user to his home page based on the userid is set or not. However, if I make get request to http://localhost:5500/ from a browser like Chrome, my server is not able to get the session with the additional property `userid' that I added when log in successfully and does not redirect my user to his home page. Can anyone explain why this happens please? Thank you
Here is the code of my index.js
`
const express = require("express")
const app = express()
const PORT = process.env.PORT || 5500
const session = require("express-session")
const { routers } = require("./routes/routes")
const mongoose = require("mongoose")
const cookieParser = require("cookie-parser")
const TIME = 1000 * 60 * 5
app.use(cookieParser())
app.use(
session({
secret: "iamnamdo1234567",
saveUninitialized: true,
cookie: { maxAge: TIME, sameSite: "strict" },
resave: false
})
)
const URI = process.env.DB_CONNECTION
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use("/api", routers)
app.get("/", (req, res) => {
let session = req.session.userid
session ? res.status(200).send("Hello my friend, you are logged in") : res.status(400).send("You need to log in")
})
mongoose.connect(URI, { useNewUrlParser: true.valueOf(), useUnifiedTopology: true }, err => {
if (err) {
console.log(err)
} else {
console.log("database connected")
}
})
app.listen(PORT, () => {
console.log(`Go to http://localhost:${PORT}`)
})
`
This is the code of my routes.js
`
const express = require("express")
const route = express.Router()
const { User } = require("../models/User")
const bcrypt = require("bcrypt")
const errorHandler = (type, error) => {
if (type === "register") {
if (error.code === 11000) {
return { message: "Username has been taken" }
} else if (error._message === "User validation failed") {
return { message: error.errors.username?.properties.message || error.errors.password?.properties.message }
}
} else if (type === "login") {
return { message: `${error}` }
}
}
route.post("/register", async (req, res) => {
try {
const { username, password } = req.body
const user = await User.create({ username, password })
res.status(200).send("User has been created successfully")
} catch (error) {
// console.log(error)
let message = errorHandler("register", error)
res.status(400).send(message)
}
})
route.post("/login", async (req, res) => {
const { username, password } = req.body
try {
const user = await User.findOne({ username })
if (!user) {
throw (new Error().message = "Username not found")
}
const checkPassword = await bcrypt.compare(password, user.password)
if (checkPassword === false) {
throw (new Error().message = "Password is incorrect")
} else {
req.session.userid = user.username
console.log(req.session.userid)
res.status(200).send("Logged in")
}
} catch (error) {
let message = errorHandler("login", error)
res.status(400).send(message)
}
})
route.post("/logout", (req, res) => {
req.session.destroy()
res.redirect("/")
})
module.exports.routers = route
`
I tried to access the session when making get request from the browser
If the session details are visible in Postman but not in the browser, it could be due to a number of reasons, one of them is Cookie policy.
By default, cookies are only sent with requests made to the same origin as the current page. To send cookies with cross-origin requests, you need to set the withCredentials option in Axios. Try this it worked for me
const axios = require('axios');
axios.defaults.withCredentials = true;
I have a Red Hat Enterpise Linux 9 server hosted at a data center, which has an Apache web server and a MySQL installation. MySQL listens on 3306, and Apache on 80 (defaults).
I'm new to React and Express, and I'm testing a client-server app. I built the client side with create-react-app, and this is the code for App.js
App.js
import "./App.css";
import { useState } from "react";
import Axios from "axios";
function App() {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [country, setCountry] = useState("");
const [position, setPosition] = useState("");
const [wage, setWage] = useState(0);
const [newWage, setNewWage] = useState(0);
const [employeeList, setEmployeeList] = useState([]);
const addEmployee = () => {
Axios.post("http://1.2.3.4:3001/create", {
name: name,
age: age,
country: country,
position: position,
wage: wage,
}).then(() => {
setEmployeeList([
...employeeList,
{
name: name,
age: age,
country: country,
position: position,
wage: wage,
},
]);
});
};
const getEmployees = () => {
Axios.get("http://1.2.3.4:3001/employees").then((response) => {
setEmployeeList(response.data);
console.log("retrieving the list");
console.log(employeeList);
});
};
getEmployees();
const updateEmployeeWage = (id) => {
Axios.put("http://1.2.3.4:3001/update", { wage: newWage, id: id }).then(
(response) => {
setEmployeeList(
employeeList.map((val) => {
return val.id == id
? {
id: val.id,
name: val.name,
country: val.country,
age: val.age,
position: val.position,
wage: newWage,
}
: val;
})
);
}
);
};
const deleteEmployee = (id) => {
Axios.delete(`http://1.2.3.4:3001/delete/${id}`).then((response) => {
setEmployeeList(
employeeList.filter((val) => {
return val.id != id;
})
);
});
};
return (
<div className="App">
<div className="information">
<label>Name:</label>
<input
type="text"
onChange={(event) => {
setName(event.target.value);
}}
/>
<label>Age:</label>
<input
type="number"
onChange={(event) => {
setAge(event.target.value);
}}
/>
<label>Country:</label>
<input
type="text"
onChange={(event) => {
setCountry(event.target.value);
}}
/>
<label>Position:</label>
<input
type="text"
onChange={(event) => {
setPosition(event.target.value);
}}
/>
<label>Wage (year):</label>
<input
type="number"
onChange={(event) => {
setWage(event.target.value);
}}
/>
<button onClick={addEmployee}>Add Employee</button>
</div>
<div className="employees">
<button onClick={getEmployees}>Show Employees</button>
{employeeList.map((val, key) => {
return (
<div className="employee">
<div>
<h3>Name: {val.name}</h3>
<h3>Age: {val.age}</h3>
<h3>Country: {val.country}</h3>
<h3>Position: {val.position}</h3>
<h3>Wage: {val.wage}</h3>
</div>
<div>
<input
type="text"
placeholder="2000..."
onChange={(event) => {
setNewWage(event.target.value);
}}
/>
<button
onClick={() => {
updateEmployeeWage(val.id);
}}
>
{" "}
Update
</button>
<button
onClick={() => {
deleteEmployee(val.id);
}}
>
Delete
</button>
</div>
</div>
);
})}
</div>
</div>
);
}
export default App;
The server is supposed to run on port 3001 of the same machine. The code for the server's index.js is below.
index.js for server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors());
app.use(express.json());
const db = mysql.createConnection({
user: "apphost",
host: "0.0.0.0",
password: "password",
database: "employeeSystem",
insecureAuth: 'true'
});
app.get('/home', (req, res) => {
res.send("HELLO THERE\n");
});
app.post("/create", (req, res) => {
const name = req.body.name;
const age = req.body.age;
const country = req.body.country;
const position = req.body.position;
const wage = req.body.wage;
db.query(
"INSERT INTO employees (name, age, country, position, wage) VALUES (?,?,?,?,?)",
[name, age, country, position, wage],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send("Values Inserted");
}
}
);
});
app.get("/employees", (req, res) => {
db.query("SELECT * FROM employees", (err, result) => {
if (err) {
console.log('server index.js problem')
console.log(err);
} else {
res.send(result);
}
});
});
app.put("/update", (req, res) => {
const id = req.body.id;
const wage = req.body.wage;
db.query(
"UPDATE employees SET wage = ? WHERE id = ?",
[wage, id],
(err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
}
);
});
app.delete("/delete/:id", (req, res) => {
const id = req.params.id;
db.query("DELETE FROM employees WHERE id = ?", id, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});
app.listen(3001, () => {
console.log("Server running on port 3001.");
});
After running the server with node index.js, when I run curl http://1.2.3.4:3001/employees from a machine on the same physical network, I get a JSON output of the data in the MySQL database as expected. From my Windows CMD, a browser on my Windows machine, or from my phone, the request times out.
Keep in mind that I'm SSH-ing to the linux VM, while on a VPN provided by the data center.
This is the error I get on chrome:
Uncaught (in promise) M {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
Not sure what the issue is. Tried a lot of solutions from all over the internet, but nothing seems to work.
If any more information is needed, feel free to ask. I'll do anything to get this issue fixed and understand what I'm doing wrong.
Thanks in advance!
I have a React.js task that requires me to make a POST request to the server. Now, I want to send a POST request when a user clicks a submit button. But I keep getting these 2 errors:
App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)
My React code:
import "./App.css";
function App() {
const [inputs, setInputs] = useState({});
const [backendData, setBackendData] = useState();
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setInputs((state) => ({ ...state, [name]: value }));
};
const handleSubmit = (e) => {
e.preventDefault();
/*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
console.log(inputs);
fetch("http://localhost:3001/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(inputs),
});
};
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
name="projectTitle"
onChange={handleChange}
className="project-title"
value={inputs.projectTitle || " "}
/>
<input
type="text"
name="id"
className="id"
onChange={handleChange}
value={inputs.id || " "}
/>
<input type="submit" value="Submit" />
</form>
</div>
);
}
export default App;
My Express code:
const express = require("express");
const app = express();
const fs = require("fs");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
var obj = { projects: [] };
app.post("/", (req, res, next) => {
let identifier = req.query.identify; //id of project
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
obj = JSON.parse(data);
obj.projects.push({
id: identifier,
title: req.query.project,
description: req.query.description,
});
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log("updatedd", req.body.inputs);
});
});
});
/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
console.log(data);
obj = JSON.parse(data);
// assign the filtered array back to the original array
obj.projects = obj.projects.filter((item) => {
let url = req.query.identify;
return item.id !== url;
});
console.log(obj);
let json = JSON.stringify(obj);
fs.writeFile("webProjects.json", json, (err) => {
if (err) throw err;
console.log(obj);
});
});
});
/*when user navigates to another page, we display the data of the resource*/
app.get("/api", (req, res, next) => {
fs.readFile("webProjects.json", (err, data) => {
if (err) throw err;
res.json(JSON.parse(data));
console.log("done");
});
});
/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get("*", (req, res, next) => {
let err = new Error("There was an error in accessing the page you wanted");
err.statusCode = 404;
next(err);
});
app.use((err, req, res, next) => {
console.log(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
let PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log("server has listened");
});
If the front end is created with create-react-app command, the problem might be the proxy one. In your package.json file, you can add proxy as shown below:
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:3001"
Before I deploy, the app performed fine on localhost. But since I deployed my frontend (react) to Netlify and backend(node/express + mysql) to Heroku, all requests sent from the frontend started to get blocked by CORS policy, with the error message:
"Access to XMLHttpRequest at 'https://xxx.herokuapp.com/login' from origin 'https://xxx.netlify.app' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://xxx.app/' that is not equal to the supplied origin."
Most importantly, the value of my Access-Control-Allow-Origin header is literally the same as the origin stated.
Originally, I've tried to use a wildcard ("*"), but it seems that due to the withCredential problem, the system just can't allow that kind of vague statement.
I've also seen many people using Netlify.toml to tackle some configuration problems, but seems ineffective for me.
Is it the header's problem? If not, then what is the problem?
I really want to know what I should do to solve this error...
The console window of the app deployed:
Cors Error
My index.js in the server folder:
const express = require('express')
const mysql = require('mysql')
const cors = require('cors')
const session = require('express-session')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const port = 3010
const app = express()
app.use(express.json())
app.use(cors({
origin: ["https://xxx.app/"], // the link of my front-end app on Netlify
methods: ["GET", "POST"],
credentials: true
}))
app.use(cookieParser())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(
session({
key: "userId",
secret: "subscribe",
resave: false,
saveUninitialized: false,
cookie: {
expires: 60 * 60 * 24
},
})
)
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "https://xxx.netlify.app/"); // the link of my front-end app on Netlify
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
res.setHeader('content-type', 'application/json');
next();
});
const db = mysql.createPool({
// create an instance of the connection to the mysql database
host: 'xxx.cleardb.net', // specify host name
user: 'xxx', // specify user name
password: 'xxx', // specify password
database: 'heroku_xxx', // specify database name
})
...
app.get('/login', (req, res) => {
if (req.session.user) {
res.send({
isLoggedIn: true,
user: req.session.user
})
} else {
res.send({
isLoggedIn: false
})
}
})
...
app.listen(process.env.PORT || port, () => {
console.log('Successfully Running server at ' + port + '.')
});
My Frontend:
import React, { useEffect, useState } from 'react'
import '../App.css'
import './HeroSection.css'
import { Link } from 'react-router-dom'
import Axios from 'axios'
function HeroSection() {
Axios.defaults.withCredentials = true
let username = "";
const [name, setName] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false)
const [isLoading, setLoading] = useState(true)
...
useEffect(() => {
Axios.get('https://xxx.herokuapp.com/login').then((response) => {
if (response.data.isLoggedIn) {
username = response.data.user[0].username;
}
setIsLoggedIn(response.data.isLoggedIn)
Axios.post('https://xxx.herokuapp.com/getLang', {
username: username,
}).then((response) => {
console.log(response.data);
})
Axios.post('https://xxx.herokuapp.com/getStatus', {
username: username,
}).then(response => {
setName(response.data[0].firstname + " " + response.data[0].lastname);
setLoading(false);
})
})
}, [])
if (!isLoggedIn || isLoading) {
return (
<div>
...
</div>
)
} else {
return (
<div>
...
</div>
)
}
}
export default HeroSection
By the way, I use ClearDB MySQL on Heroku and MySQL WorkBench for the database, which all works fine.
You could debug by doing something like:
const allowList = ["https://yyy.app/"];
// Your origin prop in cors({})
origin: function (origin, callback) {
// Log and check yourself if the origin actually matches what you've defined in the allowList array
console.log(origin);
if (allowList.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
I am trying to create an contact page using ReactJs NodeJs express and nodemail. I am not getting any error. But it's not working. The post request is not working so i guess there's something wrong with the axios function but it could be anywhere else too so.Is the error in the backend part or the frontend part How do i fix it?
Post Log saying
Proxy error: Could not proxy request /api/forma from localhost:3000 to localhost:3001 (ECONNRESET)
Client side
import React,{useState} from 'react'
import axios from 'axios';
const Form = () => {
const [name,setName] = useState("");
const [email,setEmail] = useState("");
const [message,setMessage] = useState("");
const [sent,setSent] = useState(false);
const formSubmit=(e)=> {
e.preventDefault();
let data = {
name:name,
email:email,
message:message
}
axios.post('/api/forma',data)
.then(res => {
setSent(true);
},resetForm())
.catch(() => {
console.log("message not sent");
})
}
const resetForm = () => {
setName("");
setEmail("");
setMessage("");
setTimeout(()=> {
setSent(false);
},3000)
}
return (
<div className="container">
<form onSubmit={formSubmit}>
<div className="single">
<label>Name</label>
<input type="text" name="name" className="name" placeholder="Enter your name"
value={name}
onChange={e => setName(e.target.value)}
/>
</div>
<div className="single">
<label>Email</label>
<input type="text" name="email" className="email" placeholder="Enter your email"
value={email}
onChange={e => setEmail(e.target.value)}/>
</div>
<div className="textarea">
<label>Message</label>
<textarea name="message" id="" cols ="30" rows="5" placeholder="Enter your message here"
value={message}
onChange={e => setMessage(e.target.value)}></textarea>
</div>
<div className={sent?'msg msgAppear':'msg'}>
Message has been sent
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
)
}
export default Form
Server side
const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer')
const cors = require('cors')
const app = express();
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.get('/',()=>{
resizeBy.send("Welcome")
});
app.post('/api/forma',(req,res) => {
let data = req.body
let smtptransport = nodemailer.createTransport({
service:'Gmail',
port:465,
auth:{
user:'yourEmail#gmail.com',
pass: "secreate"
}
});
let mailOptions = {
from:data.email,
to:'yourEmail#gmail.com',
subject:`Message from ${data.name}`,
html:`
<h3>Informations<h3>
<ul>
<li>Name: ${data.name}</li>
<li>Name: ${data.email}</li>
</ul>
<h3>Message<h3>
<p>${data.message}</p>
`
}
smtptransport.sendMail(mailOptions,(error,response) => {
if(error){
res.send(error)
}
else{
res.send('Success')
}
})
smtptransport.close();
})
const PORT = process.env.PORT || 3001;
app.listen(PORT,() => {
console.log(`Server starting at port ${PORT}`);
})
One way to solve this using gmail is creating a transporter.
Here is the working code:
mail.service.js
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: '<myuser>#gmail.com',
pass: '<mypassword>'
},
logger: false, // log to console
debug: false // include SMTP traffic in the logs
});
exports.sendEmail = function(req, res) {
const mailOptions = {
from: '<myuser>#gmail.com',
subject: 'My custom title ',
text: 'Mensagem de: ' + req.body.nome + ', email: [' + req.body.email + '] ' + req.body.mensagem,
to: req.body.email
}
transporter.sendMail(mailOptions).then((trans) => {
res.status(200);
res.json(trans);
res.end();
}).catch((error) => {
res.status(500);
res.json(error);
res.end();
});
}
Here is my router for sendemail action:
const router = require('express').Router();
const emailService = require('../services/mail.service.js');
router.post('/sendmail', emailService.sendEmail);
module.exports = router;
If you are in some situation of 403 errors you might need to do this configurations steps provided by nodemailer (this configuration is in gmail account) .