I have built a form which I want to be able to send emails, to do this I have attempted to follow this youtube tutorial: https://www.youtube.com/watch?v=_3-By9QfFa0
However I am running into an issue where I am getting the error in the question title which is coming up in my console web browser when trying to submit the form. I realize the issue might have something to do with one of the routes somewhere but I just cant figure it out (unless it's something completely different).
schoolForm.js
const handleSubmit = async(e) => {
e.preventDefault();
try { //I also tried using only: "/send_mail" here like I have in server.js but it didnt work
await axios.post("http://localhost:3000/send_mail", {
name
});
}
catch (error) {
console.log(error);
}
}
server.js
const express = require("express");
const app = express();
require("dotenv").config();
const bodyParser = require("body-parser");
const cors = require("cors");
const nodemailer = require("nodemailer");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(cors());
app.post("/send_mail", cors(), async (req, res) => {
let {text} = req.body;
const transport = nodemailer.createTransport({
host: "smtp-mail.outlook.com",
port: 587,
auth: {
user: "someone#hotmail.com",
pass: "password"
},
tls: {
rejectUnauthorized: false
}
});
await transport.sendMail({
from: "someone#hotmail.com",
to: "someone#hotmail.com",
subject: "subject",
html: `<p>${text}</p>`
})
});
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
Edit: The error I get in the browser:
Is there anyone that can help me solve this issue? Help would be greatly appreciated!
Your server is listening on port 4000. // server.js
app.listen(4000, () => {
console.log("Server is listening on port 4000");
});
You should use below URL for Axios call. // schoolForm.js
await axios.post("http://localhost:4000/send_mail", { // use port 4000 not 3000
name
});
You've set up your server to listen to port 4000 but your axios request is to port 3000.
Make sure you send the request to the correct port:
await axios.post("http://localhost:4000/send_mail", {
name
});
Also note the body-parser is deprecated and you should use express built-in middleware. so instead of:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
you should have:
app.use(express.urlencoded({extended: true}));
app.use(express.json());
and you can remove body-parser dependency.
You can read here to learn more about express built-in middleware and their optional properties.
EDIT:
The reason it wasn't working is because body is an object created by the middleware itself. Therefore req.body is undefined since the body object doesn't exists
Related
So after i deployed my express app to cyclic i tried to access it through my browser, but i got an error:
Cannot GET /categories
this is my code:
import express, { Request, Response } from "express";
import dotenv from "dotenv";
import bodyParser from "body-parser";
const app = express();
dotenv.config();
const port = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Routes
app.use("/categories", require("./routes/category"));
app.use("/users", require("./routes/user"));
app.use("/points", require("./routes/point"));
app.listen(port, () => {
console.log(`Running on ${port}`);
});
I tried to add GET route using
app.get("/categories", async (req: Request, res: Response) => {
res.json({ message: "hello" });
});
but it didn't work.
It has been working until i pushed it into production on cyclic. Previously thanks!
Beginner here...so bear with me :)
I'm getting this dataset in the console, but I can't wrap my head around getting it sent to the client side...
const { response } = require('express');
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
const translate = require('sdapi').default.translate;
translate('hablar').then(console.log);
This is the result I get:
[
{
word: 'hablar',
lang: 'es',
gender: undefined,
context: 'to articulate words',
meaning: 'to speak',
part: 'intransitive verb',
examples: [ [Object] ],
regions: []
}]
I've tried wraping it into a app.get('/translation', async (req, res) => {}) but it doesn't work.
Appreciate your time/attention.
app.get('/translate/:word', async (req, res) => {
const {
params: { word },
} = req; // same as const word = req.params.word
const translatedWord = await translate(word); // same as .then
return res.status(200).json({ translatedResponse: translatedWord });
});
To activate this you have to send http get request to whateverip:port/translate/<WORD_TO_TRANSLATE_INPUT>
You can send http requests with axios, curl, or fetch and your browser's terminal thouhg the last one isn't always optimal solution.
I think you want to check your controller and sed data to it
so the first step that u must do to install body-parser with npm i body-parser
then use it like
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
now u can receive and store your data on request.
then learn about the request (https://expressjs.com/en/guide/routing.html)
then u can send a request to your server with postman or Axios or curl and something else .
I hope to solve your question.
I tried to connect my mongo cluster with my local server but this error keeps on showing up. I am following a tutorial and it seems to work fine for the tutor but this error comes for me. I have provided the error screenshot below.
Error which comes up
The src has been provided
const express = require('express');
const env = require('dotenv');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
//routes
const userRoutes = require('./routes/user');
//constants
env.config();
//mongodb connect
//mongodb+srv://root:<password>#cluster0.9ylhh.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
mongoose.connect(
`mongodb+srv://${process.env.MONGO_DB_USER}:${process.env.MONGO_DB_PASSWORD}#cluster0.9ylhh.mongodb.net/${process.env.MONGO_DB_DATABASE}?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
}
).then(() => {
console.log('Database connected');
});
//middleware
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.listen(process.env.PORT, () => {
console.log(`server is running on port ${process.env.PORT}`);
});
I also did create a .env file with the credentials details and stuff
I tried to make a comment instead of an answer, but I don't have enough reputation.
If the error is authentication, maybe you have a problem with your credentials.
Does your username or password have any of these chars? : / ? # [ ] #
If they do, you'll have to URI encode them like so:
${encodeURIComponent(process.env.MONGO_DB_USER)}
${encodeURIComponent(process.env.MONGO_DB_PASSWORD)}
More info here: https://docs.mongodb.com/manual/reference/connection-string/#examples
BTW: You forgot the env part on your ${process.MONGO_DB_PASSWORD}.
I am able to retrieve(get) data from express but cannot post data to express...
client:
<html>
<button onclick="myFunction()">send</button>
<script>
const data = {"experience" : 0};
function myFunction(){
fetch("/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
}
</script>
</html>
express:
Here I was getting undefined, but when I added express.json(), I got "{}". The client's and the server's conections are good, but there is no body where the data is stored?
I made sure my client code was working fine by posting data to webhooks.site, it worked fine.
I think there is some kind of rookie mistake... Btw, I am using react and express, I just simplified my code... any suggestions will be appreciated
const express = require("express");
const app = express();
app.post("/post", express.json() ,function (req,res){
console.log(req.body)
})
const port = 5000;
app.listen(port, () => `Server running on port ${port}`);
I have had to use Body Parser (simple) or Busboy (advanced) to access data in POST body with Express.
An example might look like:
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post("/post",(req,res,next)=>{
console.log(req.body);
})
I am trying to make Postman work with React JS using express. I am following a Mern Stack Development tutorial in free code camp. I have Cors extension enabled in my browsers, both in Chrome and in Edge. I keep getting this message in localhost:5000 "Cannot get /" and get this message {"msg":"This is CORS-enabled for an allowed domain."} in localhost:5000/users/add. My code looks something like this:
This is my server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology:true});
const connection= mongoose.connection;
connection.once('open', () =>{
console.log("Mongodb database connection established successfully");
})
const exercisesRouter= require('./routes/exercises');
const usersRouter= require('./routes/users');
var allowlist = ['http://localhost:5000']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use('./exercises',exercisesRouter);
app.use('./users', usersRouter);
app.get('/users/add', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})
app.listen(port, ()=>{
console.log(`Server is running on port: ${port}`);
});
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
cords don’t have anything to do with this
Can you tell me where is yow route for “/“ something like this
app.get(“/“, (req,res)=>{
…..
});
Yes exactly. You don’t have it. If the route/endPoint is not declared how do use expect them browsers to show you some else
When browssers open yow link at localhost:5000
They make a get request to “/“. So express just tell’em
Can not get “/“
I do not