'cannot get addfriend' in express while using postrequest - node.js

This is my code app.js code
var express = require("express");
var app = express();
var bp = require("body-parser");
app.use(bp.urlencoded({extended: true}));
var friends = ["babba","lkshjk","kfhkd"];
app.get("/",function(req,res){
res.send("homepage");
});
app.get("/friends",function(req,res){
res.render("friends.ejs",{friends : friends});
});
app.post("/addfriends",function(req,res){
res.send("works fine");
});
var server = app.listen(2700 ,function() {
console.log("started");
});
and this is friends.ejs code
<h1>
friends list
</h1>
<% friends.forEach(function(friend){ %>
<li> <%= friend %> </li>
<% }); %>
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
i just need "works fine " in my '/addfriend'
but i am getting
cannot get /addfriend in chrome
this works fine in postman when i try to debug

Your form have to point to the express route.
It should be:
<form action="/addfriends" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
Instead of
<form action="/addfriend?" nature="POST">
<input type="text" ,name="nf" , placeholder="name">
<button>
submit
</button>
</form>
You should declare your route equal you did in express route:
app.post("/addfriends",function(req,res){
res.send("works fine");
});

Related

Why express call my get route and not my put route?

I have the following route in my express application:
router.get('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(searchQuery)
Address.findOne(searchQuery)
.then(address => {
res.render('myForm', {address:address});
})
.catch(err => {
console.log(err);
});
});
and my form is:
<form action="/edit/<%= address.id %>?_method=put" method="POST">
<input type="hidden" name="_method" value="PUT">
<br>
<input type="text" value="<%= address.name %>" name="name" class="form-control">
<br>
<input type="text" value="<%= address.email %>" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
It works correctly, I can see the data getting form the mongodb into myForm. Now after I update some data in this form and click the udpdate button i get : Cannot POST /edit/62185a7efd51425bbf43e21a
Noting that I have the following route:
router.put('/edit/:id', (req, res)=> {
let searchQuery = {_id : req.params.id};
console.log(`searchQuery = ${searchQuery}`)
Address.updateOne(searchQuery, {$set: {
name: _.extend(name, req.body),
email: req.body.email,
}})
.then(address => {
res.redirect('/');
})
.catch(err => {
res.redirect('/');
});
});
It looks like express call the get and not the put in my case. Any suggestion?
The browser itself will only do GET and PUT from a <form>. So, your browser is sending a POST and your server doesn't have a handler for that POST.
The ?_method=put that you added to your URL looks like you're hoping to use some sort of method conversion or override tool on the server so that it will recognize that form POST as if it were a PUT. You don't show any server-side code to recognize that override query parameter so apparently your server is just receiving the POST and doesn't have a handler and thus you get the error CANNOT POST /edit/62185a7efd51425bbf43e21a.
There are several different middleware solutions that can perform this override. Here's one from Express: http://expressjs.com/en/resources/middleware/method-override.html and you can see how to deploy/configure it in that document.
Basically, you would install the module with:
npm install method-override
and then add this to your server:
const methodOverride = require('method-override')
// override with POST having ?_method=PUT
app.use(methodOverride('_method'));
This will look at incoming POST requests with the ?_method=PUT query string and will modify the method per the parameter in the query string so that app.put() will then match it.
This is to be used when the client can only do GET or POST and can't do other useful methods such as PUT or DELETE.
As a demonstration, this simple app works and outputs got it! back to the browser and /edit/123456789?_method=put in the server console when I press the Update User button in the HTML form.
const app = require('express')();
const path = require('path');
const methodOverride = require('method-override');
app.use(methodOverride('_method'));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
app.put('/edit/:id', (req, res) => {
console.log(req.url);
res.send("got it!");
});
app.listen(80);
And, temp.html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/edit/123456789?_method=put" method="POST">
<br>
<input type="text" value="hello" name="name" class="form-control">
<br>
<input type="text" value="hello#gmail.com" name="email" class="form-control">
<br>
<button type="submit" class="btn btn-info btn-block mt-3">Update User</button>
</form>
</body>
</html>
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos.
Note: you must change the method in side form tag to PUT
<form action="/edit/<%= address.id %>" method="put">
//Backend.js
router.route('/edit/:id')
.get((req, res) => {
res.send('Get a random book')
})
.put((req, res) => {
res.send('Update the book')
})

The button in express not working for me and have no error codes

I am learning express node.js and trying to run simple calculator code but anytime i press on the button i don't get any response back and also i don't get any errors in my code so i am kind of lost of what i am doin wrong. here is the sample of it so hoping someone can pinpoint me where i am goin wrong will include html code and calculator.js. Thank you in advance.
index.html
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="button" name="submit">Calculate</button>
</form>
</body>
calculator.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
//this line to show result in hyper
console.log(req.body);
res.send("The result is: " + result);
});
app.listen(3000, function(){
console.log("Server running on port 3000");
});
the problem lies in your button type. To submit a form using a button in html, you need to specify the type not as button, but as type.
<form action="/" method="post">
<input type="text" name="num1" placeholder = "first number" value="">
<input type="text" name="num2" placeholder="second number" value="">
<button type="submit" name="submit>Calculate</button>
</form>

Form submit with bootstrap and nodejs

I am using boostrap (via MDB 4) and am trying to get the contact form to work. I have the form presenting as expected. It contains the following button outside the </form> tag
<a class="btn btn-primary" onclick="document.getElementById('contact-form').submit();">Send</a>
The opening line of the form is:
<form id="contact-form" name="contact-form" action="/contact" method="POST">
I am trying to understand how I get the form contents to nodejs and have the following in my Express routes
app.post('/contact', function(req, res){
console.log(req.body.name);
console.log(req.body.email);
console.log(req.body.subject);
console.log(req.body.message);
// code to store here later
});
I know this I am hitting this block as I can console out text from within the route but I get an error every time:
TypeError: Cannot read property 'name' of undefined
All the examples seem to use PHP but I would have thought nodejs would be more than enough for this? I don't have PHP on the box and would rather avoid it if I can stay in nodejs. Anyone got some pointers for me?
It might be worth noting that jquery is used but I don't know if that links in here? The following is at the foot of my html
<script type="text/javascript" src="js/jquery.min.js"></script>
Solved by adding the following to my index.js
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded());
Now when I console.log(req.body); is get:
{
name: 'name',
email: 'name#x.y',
subject: 'test',
message: 'test'
}
I created solution for you:
//connect express
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var partials = require('express-partials');
var app = express();
app.use(express.json());
app.use(partials());
app.use(express.urlencoded({ extended: false }));
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
//top level routing
app.get('/', (req, res) => {
res.render('index.ejs')
});
app.post('/contact', function(req, res){
res.render('thanks.ejs', {body: req.body})
});
//start server
var http = require('http');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
<!--- start index.ejs -->
<form action="/contact" method="post" class="form-signin">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" placeholder="Enter subject">
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea type="text" class="form-control" name="message" placeholder="Enter message"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<!--- end index.ejs -->
<!--- start thanks.ejs--->
<%=JSON.stringify(body)%>
<!--end thanks.ejs --->
<!--- start layout.ejs --->
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="content">
<%-body -%>
</div>
</div>
</body>
</html>
<!--- end layout.ejs --->
My answer is based on this resource https://exceed-team.com/tech/form-submit-with-bootstrap-and-nodejs

How to get POST data in request?

I'm using Express+Node.js now. I need to extract POST data from a request to make Log-in process.
I want to get POST data in request but there was nothing in req.body when I ran my code.(Always return {} )
I'm relatively new to NodeJs, so precise help is welcome. Please help me.
var express = require('express');
var router = express.Router();
var bodyparser=require('body-parser');
var crypto=require('crypto');
var passport=require('passport');
var localStrategy=require('passport-local').Strategy;
var mysql=require('mysql');
router.use(bodyparser.json());
router.use(passport.initialize());
router.use(passport.session());
var config={
///config
};
const conn = new mysql.createConnection(config);
conn.connect(function(err){
if(err){
console.log('Cannot Connect to database : ');
throw err;
}
else{
console.log('Success to connect database');
}
});
var isAuthenticated =function(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.redirect('/');
}
router.post('/login',function(req,res,next){
console.log(req.body);
});
module.exports=router;
html form code
<form class="login100-form validate-form" method="post" action="/login">
<div class="wrap-input100 validate-input" data-validate = "이메일 양식 확인">
<input class="input100" type="text" name="username">
<span class="focus-input100" data-placeholder="Email"></span>
</div>
<div class="wrap-input100 validate-input" data-validate="비밀번호 양식 확인">
<span class="btn-show-pass">
<i class="zmdi zmdi-eye"></i>
</span>
<input class="input100" type="password" name="password">
<span class="focus-input100" data-placeholder="Password"></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn">
Login
</button>
</div>
</div>
</form>
you need to send a body in your request, something like the postman tool can help you.
You need to add a body to your request and send it to your http://localhost: 3000
Use POSTMAN, insert url like this http://10.10.0.1:3000/user/login
in Body section select raw type Json
then insert
{
"email_id" : "abc123#xyz.in",
"password" : "Test#123"
}

req.body is always an empty object

I'm doing a React App + Express server,
I want to get in a route /info in my server all the infos from a form in a client,
But when I console log "req.body" in the server, I always get an empty object (see Express code below),
I tried to use body-parser but nothing changes, I don't see where's the issue,
Can somebody help me please ?
React code :
async function getResults(e) {
e.preventDefault();
const info = {
minimumPrice,
maximumPrice
};
console.log("info ", info);
try {
const data = await axios.get("http://localhost:5000/info", info);
console.log("data ", data);
setResults(data.data);
console.log("results ", data.data);
} catch (e) {
console.error(e);
}
}
<form onSubmit={getResults} autoComplete="off" method="get">
<div className="row">
<div className="input-field col s12">
<input
id="minimum-price"
type="number"
name="minimumPrice"
placeholder="Entrez votre prix minimum"
value={minimumPrice}
onChange={e => setMinimumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix minimum</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input
id="maximum-price"
type="number"
name="maximumPrice"
placeholder="Entrez votre prix maximum"
value={maximumPrice}
onChange={e => setMaximumPrice(e.target.value)}
style={{ backgroundColor: "transparent !important" }}
required
/>
<label htmlFor="email">Prix maximum</label>
</div>
</div>
<div className="row">
<div className="col s12" style={{ textAlign: "center" }}>
<button
className="btn waves-effect waves-light"
type="submit"
name="action"
>
Rechercher
<i className="material-icons right">send</i>
</button>
</div>
</div>
</form>
Express code :
const express = require("express");
const app = express();
const leboncoin = require("leboncoin-api");
const cors = require("cors");
const bodyParser = require("body-parser");
app.use(cors());
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.use(bodyParser.json());
app.get("/info", (req, res) => {
console.log("body ", req.body); <---------- ALWAYS AN EMPTY OBJECT
}
You are making a get request with axios. The parameters sent with get request are available in req.query.
Parameters passed with post request are received in req.body.

Resources