XHR POST 404 error when using fetch api with NodeJS and Express - node.js

I am currently learning how to use the fetch api for my front-end. I continue to get the XHR 404 POST error.
//Backend file
const express = require("express");
const app = express();
require("dotenv");
const Port = process.env.PORT || 5000;
app.use(express.static("public"));
app.use(express.json());
app.use(
express.urlencoded({
extended: false,
})
);
const nodemailer = require("nodemailer");
const Mail = require("nodemailer/lib/mailer");
require("nodemailer-mailgun-transport");
app.use(express.json());
app.get("/", (req, res) => {
res.sendFile("/public");
res.sendFile("/public/js/mail.js");
});
app.listen(Port, (req, res) => {
console.log(`listening on port ${Port}`);
});
app.post("/email"),
(req, res) => {
FromMailjs = req.body;
console.log(FromMailjs);
const transporter = nodemailer.createTransport({
auth: {
user: process.env.Email,
pass: process.env.Pass,
},
});
const MailOptions = {
from: req.body.Email,
to: process.env.MyEmail,
text: `${req.body.FirstName}, ${req.body.LastName}
, ${req.body.PhoneNumber}, ${req.body.Email}`,
};
transporter.sendMail(MailOptions, (error, info) => {
if (error) {
console.log(error);
res.send("error");
} else {
console.log("Email sent");
res.send("success");
}
});
};
//Frontend file
const ContactForm = document.querySelector(".contact-form");
ContactForm.addEventListener("submit", (e) => {
e.preventDefault();
let FirstName = document.getElementById("Fname");
let LastName = document.getElementById("Lname");
let PhoneNumber = document.getElementById("PhoneNumber");
let Email = document.getElementById("Email");
const FormData = {
FirstName: FirstName.value,
LastName: LastName.value,
PhoneNumber: PhoneNumber.value,
Email: Email.value,
};
const PostOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(FormData),
};
console.log(FormData);
fetch("/email", PostOptions);
});
XHRPOSThttp://localhost:5000/email
[HTTP/1.1 404 Not Found 27ms]
I have tried changing the routes hoping that it was just a routing issue and I still get the same error. I was using XHR before fetch and I got the same 404 error. My front-end is receiving the correct information but I can't get my backend to receive the information.

You have a typo. Please use:
app.post("/email", (req, res) => {
Instead of:
app.post("/email"),
(req, res) => {

Related

Fetching twilio api from node js is not working & throwing error

In this code i have added express endpoints to get twilio endpoints
const config = require("./config");
const express = require("express");
const bodyParser = require("body-parser");
const pino = require("express-pino-logger")();
const { videoToken } = require("./tokens");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(pino);
const sendTokenResponse = (token, res) => {
res.set("Content-Type", "application/json");
res.send(
JSON.stringify({
token: token.toJwt(),
})
);
};
app.post("/video/token", (req, res) => {
const identity = req.body.identity;
const room = req.body.room;
const token = videoToken(identity, room, config);
sendTokenResponse(token, res);
});
In this code i have added function to fetch twilio endpoints but i don't know why it's throwing error of JSON unexpected token at position 0 maybe it's twilio error
const handleSubmit = useCallback(async () => {
setConnecting(true);
const data = await fetch("/video/token", {
method: "POST",
body: JSON.stringify({
identity: username,
room: roomName,
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}).then((res) => res.json());
Video.connect(data.token, {
name: roomName,
})
.then((room) => {
setConnecting(false);
setRoom(room);
})
.catch((err) => {
console.error(err);
setConnecting(false);
});
}, [roomName, username]);

Add subscriber to my mailchimp subscriber list

I am new to backend web development and trying to create subscriber through a sign up page and add them to my Mailchimp through API but I am not been able to create subscriber (subscribers are not adding in my Mailchimp audience list). Below is my code.
const port = 3000;
const https = require('node:https');
const express = require('express');
const app = express();
app.use(express.static("public"));
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', (req, res) => {
res.sendFile(__dirname + "/signup.html")
});
app.post('/', (req, res) => {
const email = req.body.emailId;
const firstName = req.body.firstName;
const lastName = req.body.lastName;
var data = {
members: [{
email_address: email,
status: "Subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
const jsonData = JSON.stringify(data);
const url = "https://us11.api.mailchimp.com/3.0/lists/"list_id"/";
const options = {
method: "POST",
auth: "dALamyan:apiKey"
};
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end;
});
app.listen(port, () => {
console.log("app listening on port 3000.");
});
You can try my code below. It's working fine for me.
Change X in the API endpoint, listID and apiKey as per your account settings.
Cheers.
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const https = require("https");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", (req, res) => {
const firstName = req.body.firstname;
const lastName = req.body.lastname;
const email = req.body.email;
const data = {
members: [{
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: firstName,
LNAME: lastName
}
}]
};
const jsonData = JSON.stringify(data);
const url = "https://usX.api.mailchimp.com/3.0/lists/" + listID;
const options = {
method: "POST",
auth: "archit:apiKey"
}
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
});
});
request.write(jsonData);
request.end();
});
app.listen("3000", (req, res) => {
console.log("Server is running on port 3000.");
});

Nodemailer contact form works locally but gives an error in deployment

I created a contact form to learn to use nodemailer and in my localhost it works, but after deploying it to Heroku, each time it gives me this error: {"code":"EAUTH","command":"API"}
Here is my code:
const express = require('express');
const app = express();
const path = require('path');
const nodemailer = require('nodemailer');
const PORT = process.env.PORT || 3000;
// Middlewares
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
app.get('/', (req, res) => {
res.sendFile('index.html');
});
app.post('/', (req, res) => {
console.log(req.body);
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});
const mailOptions = {
from: req.body.email,
to: process.env.MAIL_USER,
subject: `Message from ${req.body.name}`,
text: `
from: ${req.body.name}
email: ${req.body.email}
${req.body.message}`
}
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.send(error);
}
else {
console.log('Email sent: ' + info.response);
res.send('success');
}
})
});
app.listen(PORT, () => {
console.log(`server at port ${PORT}`);
});
This is the link to the website: https://nodejs-contactform.herokuapp.com/
Any help will be highly appreciated.

**No 'Access-Control-Allow-Origin' header is present on the requested resource.**

In local server nodemailer sending all mails but on production
throws console error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
node backend deployed at heroku + react app on netlify
//react app axios post method for sending user data
const sendMail = async() => {
await axios
.post("https://xxxxxxx.herokuapp.com/email", {
username: username,
senderemail: email,
subject: subject,
message: message,
})
.then((res) => {
res.status === 200 ? alert("Message sent!") : alert("Try again!");
})
.catch((err) => console.error(err));
};
express app.js file
these are my code snippets of express backend
console error
nodemailer snippet module:
const nodemailer = require("nodemailer");
require("dotenv").config();
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.G_USER,
pass: process.env.G_PASS,
},
});
module.exports = transporter;
express code snippet:
const express = require("express");
const cors = require("cors");
const app = express();
const transporter = require("./mail");
const PORT = process.env.PORT || 5000;
app.use(
cors({
origin: "https://xxxxxx.netlify.app",
optionsSuccessStatus: 200,
})
);
app.use(express.json());
app.get("/", (req, res) => {
res.send("node is up!");
});
app.post("/email", async (req, res) => {
const username = req.body.username;
const senderemail = req.body.senderemail;
const subject = req.body.subject;
const message = req.body.message;
const mailOptions = {
from: username,
to: "xxxxxxx#gmail.com",
subject: subject,
html: `
<p>${message}</p>
<address>By: ${username} <br/> ${senderemail}<address/>
`,
};
await transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.error(err.message);
} else {
res.json(info.response);
}
});
});
app.listen(PORT, () => {
console.log(`Server is up!`);
});
I suggest you try to make it first work by joust doing cors() and then whitelist the domain. If you are still not able to make it work, you can use the below solution. But please don't forget to properly whitelist the domains.
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Expose-Headers', 'Content-Type');
if(req.method === 'OPTIONS') {
res.writeHead(200);
return res.end();
} else {
return next();
}
});
https://accounts.google.com/DisplayUnlockCaptcha
hey guys if you are you using nodemailer Gmail service and having the same issue click on above link to unlock CAPTCHA....
because gmail block third party applications to send emails....
by allowing access my code is working fine!!!

What could be the reason for getting 500 server error?

Im trying to integrate stripe payment using axios with node.js but at the end Im getting back an error message: Request failed with status code 500, although in the request payload I do see a token data filled properly.
here is my node.js code:
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const path = require("path");
if (process.env.NODE_ENV !== "production") require("dotenv").config();
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === "production") {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("*", function (req, res) {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});
}
app.listen(port, (error) => {
if (error) throw error;
console.log("Server running on port " + port);
});
app.post("/payment", (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: "eur",
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ success: stripeRes });
}
});
});
and here is my client side code using axios library and stripe-checkout pre-built component
const priceForStripe = price * 100;
const publishableKey = "pk_test_i28ouERO9Dli1OlxDdGM7HFA00hCEjnkrw";
const onToken = (token) => {
axios({
url: "/payment",
method: "POST",
headers: { "content-type": "application/json" },
data:{
amount: priceForStripe,
token,
},
})
.then((response) => {
alert("Payment was successfull !!");
})
.catch((error) => {
console.log("Payment error:", error);
alert("There was an issue with your payment");
});
};
return (
<StripeCheckout
label="PAY NOW"
name="Shibukas&Co"
billingAddress
shippingAddress
image="https://sendeyo.com/up/d/f3eb2117da"
description={`Your total price is €${price}`}
amount={priceForStripe}
panelLabel="Pay Now"
token={onToken}
stripeKey={publishableKey}
/>
);
};```

Resources