POST http://localhost:4200/contact/send 404 (Not Found) - node.js

I have a bootstrap form for email services for angular 6 app and nodejs, I am using nodemailer for sendemail in my app, unfortunatelly does not work. I am getting the following error when I submit the form:
zone.js:2969 POST http://localhost:4200/contact/send 404 (Not Found)
here is the form HTML
<form [formGroup]="angForm" novalidate method="POST">
<div class="message">
<h3> Write to us </h3>
</div>
<div class="form__top">
<div class="form__left">
<div class="form__group">
<input class="form__input form__input--name" type="text" formControlName="name" placeholder="name" #name>
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form__group">
<input class="form__input form__input--email" type="email" formControlName="email" placeholder="email" #email>
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
<div class="form__right">
<div class="form__group">
<textarea class="form__input form__input--textarea" placeholder="Message" formControlName="message" #message
rows="3"></textarea>
</div>
<div *ngIf="angForm.controls['message'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
</div>
<flash-messages></flash-messages>
<div class="form__down">
<div class="form__group">
<button (click)="sendMail(name.value, email.value, message.value)" [disabled]="angForm.pristine || angForm.invalid" class="form__input form__input--submit" name="submit" type="submit" value="SEND MESSAGE">SEND MESSAGE
</button>
</div>
</div>
</form>
Here is component.ts
import { Component, OnInit } from '#angular/core';
import { ContactService } from '../../contact.service';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { FlashMessagesModule, FlashMessagesService } from 'angular2-flash-messages';
#Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class FooterComponent implements OnInit {
angForm: FormGroup;
constructor(
private flashMessages: FlashMessagesService,
private fb: FormBuilder,
private contactService: ContactService) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
name: ['', Validators.required],
email: ['', Validators.required],
message: ['', Validators.required],
});
}
sendMail(name, email, message) {
this.contactService.sendEmail(name, email, message).subscribe(success => {
this.flashMessages.show('You are data we succesfully submitted', { cssClass: 'alert-success', timeout: 3000 });
console.log(success);
}, error => {
this.flashMessages.show('Something went wrong', { cssClass: 'alert-danger', timeout: 3000 });
});
}
ngOnInit() {
}
}
Here is service.ts
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import { Jsonp } from '#angular/http';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '#angular/common/http';
import { Observable } from '../../node_modules/rxjs';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const apiUrl = 'http://localhost:4200/contact';
#Injectable({
providedIn: 'root'
})
export class ContactService {
sendEmailUrl = '/send';
constructor(private http: Http) { }
sendEmail(name, email, message): Observable<any> {
const uri = `${apiUrl + this.sendEmailUrl}`;
const obj = {
name: name,
email: email,
message: message,
};
return this.http.post(uri, obj);
}
}
Here is the server .js
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
// CORS Middleware
app.use(cors());
// Port Number
const port = process.env.PORT || 3000
// Run the app by serving the static files
// in the dist directory
app.use(express.static(path.join(__dirname, '/majeni/dist/majeni')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
//routes
const contact = require('./app/routes/contact');
app.use('/contact', contact);
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res, next) {
res.sendFile(path.join(__dirname + '/majeni/dist/majeni/index.html'));
});
// Start Server
app.listen(port, () => {
console.log('Server started on port ' + port);
});
Here is contact.js (routes settings)
const express = require('express');
const router = express.Router();
const request = require('request');
const nodemailer = require('nodemailer');
router.post('/send', (req, res) => {
const outputData = `
<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>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: false,
port: 25,
auth: {
user: 'Myemail',
pass: 'my pass'
},
tls: {
rejectUnauthorized: false
}
});
let HelperOptions = {
from: '"Jini" <myEmail',
to: 'myEmail',
subject: 'Majeni Contact Request',
text: 'Hello',
html: outputData
};
transporter.sendMail(HelperOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("The message was sent!");
console.log(info);
});
});
module.exports = router;
what is missing in my code?

The port of your server is 3000
const port = process.env.PORT || 3000
so you have to change this:
const apiUrl = 'http://localhost:4200/contact';
to
const apiUrl = 'http://localhost:3000/contact';

Related

Cookie error in node.JS app with next.js client program

I am actually write a node.JS application on natours project. It is actually a course project that was designed by jonas. I am designing a next.JS client side program of this backend program. Problem was that when I submit a request on http://localhost:3000/api/v1/users/signup url everything is ok, cookie is set but when I send a request on others url on this server like http://localhost:3000/api/v1/tours cookie is not read by the server and req.cookies is null. I am trying to solve this problem but I am stuck.
app.js Code
const express = require("express");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const rateLimit = require("express-rate-limit");
const helmet = require("helmet");
const xss = require("xss-clean");
const mongoSanitize = require("express-mongo-sanitize");
const hpp = require("hpp");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const globalErrorHandler = require("./controllers/errorController");
const tourRouter = require("./routes/tourRoutes");
const userRouter = require("./routes/userRoutes");
const reviewRouter = require("./routes/reviewRoutes");
const AppError = require("./utils/appError");
const app = express();
app.set("view engine", "pug");
app.set("views", `${__dirname}/views`);
// GLOBAL MIDDLEWARE
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}
const limiter = rateLimit({
max: 100,
windowMs: 60 * 60 * 1000,
message: "Too many requests from this IP, Please try again in an hour.",
});
app.use(cors({ credentials: true, origin: "http://localhost:3001" }));
app.use(helmet());
app.use(xss());
app.use("/api", limiter);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: "10kb" }));
app.use(express.static(`${__dirname}/public`));
app.use(mongoSanitize());
app.use(
hpp({
whitelist: [
"duration",
"ratingsQuantiry",
"ratingsAverage",
"difficulty",
"maxGroupSize",
"price",
],
})
);
app.use((req, res, next) => {
req.requestTime = Date.now();
console.log(req.cookies.jwt);
next();
});
app.get("/", (req, res) => {
res.status(200).render("base", {
title: "Natours",
});
});
app.use("/api/v1/tours", tourRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/reviews", reviewRouter);
app.all("*", (req, res, next) => {
// res.status(404).json({
// status: "fail",
// message: `Can't find ${req.originalUrl} on ther server.`,
// });
const err = new AppError(
`Can't find ${req.originalUrl} on ther server.`,
404
);
next(err);
});
app.use(globalErrorHandler);
module.exports = app;
Client Code in Next.js
import React, { useState } from "react";
import axios from "axios";
import Layout from "../components/Layout";
const url = "http://localhost:3000/api/v1/users/signup";
const styles = {
"input-group": "flex flex-col gap-3",
"input-label": "px-2 text-md font-thin",
"text-input": "px-2 py-4",
button:
"px-4 py-3 font-thin uppercase text-md bg-teal-700 hover:bg-teal-600 text-slate-50 rounded-sm",
"cancle-button": "bg-red-700 hover:bg-red-600",
};
function Register() {
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
passwordConfirm: "",
photo: "",
});
const handleChange = (event) => {
setFormData({
...formData,
[event.target.name]: event.target.value,
});
};
const handleSubmit = async (event) => {
event.preventDefault();
axios
.post("http://localhost:3000/api/v1/users/signup", formData, {
withCredentials: true,
})
.then((response) => console.log(response))
.catch((err) => console.log(err));
alert(JSON.stringify(formData));
};
const handleReset = (event) => {
setFormData({
name: "",
email: "",
password: "",
passwordConfirm: "",
photo: "",
});
};
return (
<Layout>
<div className="p-10 bg-slate-50">
<form onSubmit={handleSubmit}>
<h1 className="text-2xl mb-5 text-teal-700">Register your account</h1>
<div className="w-1/2 flex flex-col gap-3">
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Name</label>
<input
className={styles["text-input"]}
placeholder="Enter your name"
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Email</label>
<input
className={styles["text-input"]}
placeholder="Enter your email"
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Password</label>
<input
className={styles["text-input"]}
placeholder="Enter your password"
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
</div>
<div className={styles["input-group"]}>
<label className={styles["input-label"]}>Confirm Password</label>
<input
className={styles["text-input"]}
placeholder="Enter your confirm password"
type="password"
name="passwordConfirm"
value={formData.passwordConfirm}
onChange={handleChange}
required
/>
</div>
</div>
<div className="bg-slate-100 flex gap-3 mt-5 px-3 py-6 w-1/2">
<button className={styles.button} type="submit">
Register
</button>
<button
className={`${styles.button} ${styles["cancle-button"]}`}
type="reset"
onClick={handleReset}
>
Cancle
</button>
</div>
</form>
</div>
</Layout>
);
}
export default Register;

Express server communicating with React App

I am trying to redirect to my React App after authenticating the login.
But its not working, don't know why.
React App at port 3000
Server at port 3001
I am routing to server on login submit -> server authenticate using passport -> it should redirect to React App route '/secured'. Instead it is showing GET http://localhost:3001/secured 404 (Not Found)
It is routing to the server address. How to resolve this?
Authentication is working fine. I have checked it all using postman.
EXPRESS SERVER
//middleware
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cors({
origin: 'http://localhost:3000', //location of frontend app (react app here)
credentials: true,
}))
app.use(expressSession({
secret: 'secret',
resave: true,
saveUninitialized: true,
}))
app.use(cookieParser('secret'))
app.use(passport.initialize())
app.use(passport.session())
require('./models/passport-config')(passport)
// routes
app.get('/', (req, res) => {
res.send('Home route')
})
app.post('/login', (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) { return next(err) }
if (!user) { return res.redirect('/') }
req.logIn(user, (err) => {
if (err) { return next(err) }
return res.redirect('/secured')
})
})(req, res, next)
})
app.post('/register', (req, res) => {
console.log(req.body)
})
app.get('/user', (req, res) => {
res.send(req.user)
})
// server init
app.listen(3001, () => {
console.log('serving at http://localhost:3001...')
})
"REACT APP - App.js
import './App.css';
import Register from './components/Register';
import Login from './components/Login';
import {BrowserRouter, Route} from 'react-router-dom'
function App() {
return (
<div className="App">
<BrowserRouter>
<div>
<Route exact path="/" component={Login} />
<Route path="/secured" component={Register} />
</div>
</BrowserRouter>
</div>
);
}
export default App;
REACT APP - Login.js
import React, { Component } from 'react'
import "./login.css"
import axios from 'axios'
class Login extends Component {
constructor(props) {
super(props)
this.state = {
username: null,
password: null,
}
}
handleChange = (event) => {
event.preventDefault()
this.setState({
...this.state,
[event.target.name]: event.target.value,
})
}
handleSubmit = (event) => {
event.preventDefault()
axios({
method: "post",
data: this.state,
withCredentials: true,
url: 'http://localhost:3001/login'
})
// .then(this.getData())
}
getData = () => {
axios({
method: "get",
data: this.state,
withCredentials: true,
url: 'http://localhost:3001/user'
}).then(res => {
this.setState({
username: res.data['0'].username,
email: res.data['0'].email,
password: null
});
})
}
render() {
return (
<div >
<div>
<form id='login' onSubmit={this.handleSubmit}>
<div>
<h3>Login</h3>
</div>
<div >
<div >
<input onChange={this.handleChange} id="icon_prefix" type="text" name='username' />
<label htmlFor="icon_prefix">Username</label>
</div>
</div>
<div>
<div >
<input onChange={this.handleChange} id="icon_prefix" type="password" name='password' />
<label htmlFor="icon_prefix2">Password</label>
</div>
</div>
<div >
<div >
<input type='submit' />
</div>
</div>
</form>
<div>
Already a member? Register here
</div>
</div>
</div>
)
}
}
export default Login
Inside your handleSubmit function in your <Login /> component, you should add the .then() callback, check the response for error/success and then either show an error to the user in the UI or use React Router History to push or replace the current route.
Another option would maybe be to store a state variable in your <Login /> component, like this.state.isAuthenticated which you could then check in your render() method and choose to return a React Router Redirect like:
render() {
if (this.state.isAuthenticated) {
return <Redirect to="/somewhere/else" />
}
return (
<div>
...
</div>
)
}

How to send data from React to Express

I'm trying to create login/registration for an app using React/Node/Express/Postgres. Where I'm getting stuck is receiving data on the server side from my form in React.
I have a register component for the form in register.js
import React from 'react';
import useForm from '../form/useForm';
const Register = () => {
const { values, handleChange, handleSubmit } = useForm({
name: '',
email: '',
password: "",
password2: ""
}, register);
function register() {
console.log(values);
}
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i className="fas fa-user-plus"></i> Register
</h1>
<form
action="/users/register"
method="POST"
onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
className="form-control"
type="name"
name="name"
onChange={handleChange}
placeholder="Enter Name"
value={values.name}
required />
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
className="form-control"
type="email"
name="email"
onChange={handleChange}
placeholder="Enter Email"
value={values.email}
required />
</div>
<div className="form-group">
<label htmlFor="email">Password</label>
<input
className="form-control"
type="password"
name="password"
onChange={handleChange}
placeholder="Create Password"
value={values.password}
required />
</div>
<div className="form-group">
<label htmlFor="email">Confirm Password</label>
<input
className="form-control"
type="password"
name="password2"
onChange={handleChange}
placeholder="Confirm Password"
value={values.password2}
required />
</div>
<button type="submit" className="btn btn-primary btn-block">
Register
</button>
</form>
<p className="lead mt-4">Have An Account? Login</p>
</div>
</div>
</div>
);
};
export default Register;
A hook to handle the form actions in useForm.js
import {useState, useEffect} from 'react';
const useForm = (initialValues, callback) => {
const [hasError, setErrors] = useState(false);
const [values, setValues] = useState(initialValues);
const handleSubmit = (event) => {
if (event) event.preventDefault();
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(setValues(values => ({ ...values, [event.target.name]: event.target.value })))
}
fetch("/users/register", options)
}
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
}
};
export default useForm;
Then I have a file to manage the routes for logging in/registering in users.js
const express = require("express");
const Router = require("express-promise-router");
const db = require("../db");
const router = new Router();
//Login page
router.get('/login', (req, res) => res.send("Login"));
//Register page
router.get('/register', (req, res) => res.send("Register"));
//Register Handle
router.post('/register', (req, res) => {
console.log(req.body);
res.send('hecks');
});
module.exports = router;
I have tried messing with things inside of the handleSubmit function in my useForm.js hook, but everything leads to the console.log(req.body) from my users.js file to return as undefined. Where am I going wrong?
Edit #1: Snip from Postman sending post request
Edit #2: basic project structure
.
./client
./client/src
./client/src/components
./client/src/components/register
./client/src/components/register/register.js
./client/src/components/form
./client/src/components/form/useForm.js
./client/src/App.js
./routes
./routes/index.js
./routes/users.js
./server.js
Edit #3: Main server.js file
const express = require("express");
const mountRoutes = require("./routes");
const app = express();
mountRoutes(app);
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//catch all other routes
app.get("*", function(req, res) {
res.send("<h1>Page does not exist, sorry</h1>");
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
You’re setting state in JSON.stringify which returns undefined. you’ve to pass values in it:
const handleSubmit = (event) => {
if (event) event.preventDefault();
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values)
}
fetch("/users/register", options)
}
You need to apply bodyParser before mounting routes.
So change like this:
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mountRoutes(app);
You don't use then or await in the handleSubmit function which may cause problem.
Can you update the handleSubmit function like this and try?
const handleSubmit = async event => {
if (event) event.preventDefault();
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values)
};
try {
const response = await fetch("/users/register", options);
const responseData = await response.json();
if (response.ok) {
console.log("response ok");
callback();
} else {
console.log("response NOT ok");
throw new Error(responseData.message);
}
} catch (err) {
console.log(err);
if (err.response) {
console.log(err.response.data);
}
}
};
πŸ‘¨β€πŸ« You can try with this code below:
userForm.js: Make sure your handleSubmit in your userForm.js it's looks like this code below: πŸ‘‡
const handleSubmit = async(event) => {
if (event) event.preventDefault();
const options = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values)
}
try {
// change with your endpoint
const endpoint = 'http://localhost:3001/users/register';
const result = await fetch(endpoint, options);
// send value to your register function
callback(result);
} catch (ex) {
console.log('Something failed');
console.log(ex);
}
}
You've to use callback(result), so you can console.log that value on your register function.
express server: Make sure in your express server, you've been add body-parser, it's will looks like this code below: πŸ‘‡
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
That code above will make your req.body works.
I hope it can help you πŸ™.

How to send contact form details to email in angular 6?

I am using a contact form in my application.In this i am sending the contact form details on a particular email id. All this i have to do in angular 6. I have tried this using nodemailer but not getting proper procedure to implement it. Thanks in advance
this is support.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { client, response } from '../../interface'
import { ClientService } from '../../services/client.service'
import { EmailService } from '../../services/email.service'
import { Store } from '#ngrx/store'
import { AppState } from '../../app.state'
#Component({
selector: 'app-support',
templateUrl: './support.component.html',
styleUrls: ['./support.component.css']
})
export class SupportComponent implements OnInit {
angForm: FormGroup;
osVersion: {};
browserName: {};
browserVersion: {};
userAgent: {};
appVersion: {};
platform: {};
vendor: {};
osName : {};
clientList: client[]
clientListLoading: boolean = false;
orgMail: any;
user: any;
constructor(public clientService: ClientService,private store: Store<AppState>,
private fb: FormBuilder,
private emailService: EmailService) {
store.select('client').subscribe(clients => this.clientList = clients.filter(cli => cli.enabled == 0))
this.user = JSON.parse(localStorage.getItem('user'))
console.log(this.user);
{
this.createForm();
}
}
createForm() {
this.angForm = this.fb.group({
name: ['', Validators.required],
email: ['', Validators.required],
message: ['', Validators.required],
});
}
sendMail(name, email, message) {
this.emailService.sendEmail(name, email, message).subscribe(success => {
console.log(success);
}, error => {
console.log(error);
});
}
ngOnInit() {
// this.browser_details();
}
}
Html File:
<form [formGroup]="angForm" novalidate>
<div class="message">
<h3> Write to us </h3>
</div>
<div class="form__top">
<div class="form__left">
<div class="form__group">
<input class="form__input form__input--name" type="text" formControlName="name" placeholder="name" #name>
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form__group">
<input class="form__input form__input--email" type="email" formControlName="email" placeholder="email" #email>
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
<div class="form__right">
<div class="form__group">
<textarea class="form__input form__input--textarea" placeholder="Message" formControlName="message" #message
rows="3"></textarea>
</div>
<div *ngIf="angForm.controls['message'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
</div>
<div class="form__down">
<div class="form__group">
<button (click)="sendMail(name.value, email.value, message.value)" [disabled]="angForm.pristine || angForm.invalid" class="form__input form__input--submit" name="submit" type="submit" value="SEND MESSAGE">SEND MESSAGE
</button>
</div>
</div>
contact.js
const express = require('express');
const router = express.Router();
const request = require('request');
const nodemailer = require('nodemailer');
const cors = require('cors');
router.options('/send', cors());
router.get('/send', cors(), (req, res) => {
const outputData = `
<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>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
let transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: false,
port: 25,
auth: {
user: 'email',
pass: 'pass'
},
tls: {
rejectUnauthorized: false
}
});
let HelperOptions = {
from: '"kutomba" <email',
to: 'email',
subject: 'Majeni Contact Request',
text: 'Hello',
html: outputData
};
transporter.sendMail(HelperOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("The message was sent!");
console.log(info);
});
});
module.exports = router;
server.js
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
// CORS Middleware
app.use(cors());
// Port Number
const port = process.env.PORT || 3000
// Run the app by serving the static files
// in the dist directory
app.use(express.static(path.join(__dirname, '/majeni/dist/majeni')));
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//routes
const contact = require('./app/components/support/contact');
app.use('/contact', contact);
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app
// to use the forceSSL
// middleware
// app.use(forceSSL());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/majeni/dist/majeni/index.html'));
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
This my email.service.ts
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
#Injectable({
providedIn: 'root'
})
export class EmailService {
constructor(private http: Http) { }
sendEmail(name, email, message) {
const uri = 'http://localhost:4200/support/contact';
const obj = {
name: name,
email: email,
message: message,
};
return this.http.post(uri, obj);
}
}
You should not use two ports on contact.js and the port 465 is the port secure so replace:
port: 465,
secure: false,
port: 25,
auth: {
user: 'email',
pass: 'pass'
},
tls: {
rejectUnauthorized: false
}
for:
port: 465,
secure: true,
auth: {
user: email,
pass: pass
}
On the variables email and pass you should set the email and password of account who go sent the email (I recommended create a new email account just for the form contact because gmail accounts by default not allows clients login without set up DMARK e DKIM) and always make sure to keep this informations out of public code repositories like GitHub.
You can see a similar code who I did on my github: https://github.com/anajuliabit/my-website-backend/blob/master/src/Controllers/ContactController.js

Failed to load resource: net::ERR_CONNECTION_REFUSED : Nodejs

I have a bootstrap form for email services for angular 6 app and nodejs, I am using nodemailer for sendemail in my app, unfortunatelly does not work. I ma getting the following error:
Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1
here is the form
<form [formGroup]="angForm" novalidate>
<div class="message">
<h3> Write to us </h3>
</div>
<div class="form__top">
<div class="form__left">
<div class="form__group">
<input class="form__input form__input--name" type="text" formControlName="name" placeholder="name" #name>
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form__group">
<input class="form__input form__input--email" type="email" formControlName="email" placeholder="email" #email>
</div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
<div class="form__right">
<div class="form__group">
<textarea class="form__input form__input--textarea" placeholder="Message" formControlName="message" #message
rows="3"></textarea>
</div>
<div *ngIf="angForm.controls['message'].invalid && (angForm.controls['message'].dirty || angForm.controls['message'].touched)"
class="alert alert-danger">
<div *ngIf="angForm.controls['message'].errors.required">
message is required.
</div>
</div>
</div>
</div>
<flash-messages></flash-messages>
<div class="form__down">
<div class="form__group">
<button (click)="sendMail(name.value, email.value, message.value)" [disabled]="angForm.pristine || angForm.invalid" class="form__input form__input--submit" name="submit" type="submit" value="SEND MESSAGE">SEND MESSAGE
</button>
</div>
</div>
</form>
Here is contact,js (node mailer settings and routes)
const express = require('express');
const router = express.Router();
const request = require('request');
const nodemailer = require('nodemailer');
router.get('/send', (req, res) => {
const outputData = `
<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>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
let transporter = nodemailer.createTransport({
service: 'gmail',
secure: false,
port: 25,
auth: {
user: 'MY EMAIL',
pass: 'THE PASSWORD'
},
tls: {
rejectUnauthorized: false
}
});
let HelperOptions = {
from: '"MYNAME" <MYEMAIL,
to: 'MYEMAIL',
subject: 'Majeni Contact Request',
text: 'Hello',
html: outputData
};
transporter.sendMail(HelperOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("The message was sent!");
console.log(info);
});
});
module.exports = router;
here is the server js.
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const app = express();
// Port Number
const port = process.env.PORT || 3000
// Run the app by serving the static files
// in the dist directory
app.use(express.static(path.join(__dirname, '/majeni/dist/majeni')));
// Body Parser Middleware
app.use(bodyParser.json());
//routes
const contact = require('./app/routes/contact');
app.use('/contact', contact);
// CORS Middleware
app.use(cors());
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function () {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app
// to use the forceSSL
// middleware
app.use(forceSSL());
// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname + '/majeni/dist/majeni/index.html'));
});
// Start Server
app.listen(port, () => {
console.log('Server started on port '+port);
});
UPDATE
Here is service
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import { Jsonp } from '#angular/http';
#Injectable({
providedIn: 'root'
})
export class ContactService {
constructor(private http: Http) { }
sendEmail(name, email, message) {
const uri = 'http://localhost:3000/contact/send';
const obj = {
name: name,
email: email,
message: message,
};
return this.http.post(uri, obj);
}
}
What is missing in my code?
Failed to load resource: net::ERR_CONNECTION_REFUSED : :3000/contact/send:1
Your error means your client application is Unable to connect to your nodejs server.
Fix
Your code :
const uri = 'http://localhost:3000/contact/send';
Will work if nodejs server is running on port 3000 on localhost.
For anyone else getting this error.
Check that your NodeJS is not crashing. If a previous request causes your NodeJS server to crash or restart this is the same error on subsequent requests.
make sure your spring boot project is also running with angular project.

Resources