express post method and body.req does not work - javascript

I am trying to get "POST" method form data from HTML form using app.post method but I can catch anything to req.body. What am I doing wrong?
My html form -
<form method="POST" action="/success.html">
<div id="input-area">
<textarea id="title" name="title" rows="1" cols="75" placeholder="Title" onkeyup="instance.tweaker()"></textarea>
<textarea rows="10" type="text" cols="75" placeholder="Description" name="description"></textarea>
<div id="calender"><input id="dater" type="date" value=""></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
<script src="backend2.js" defer></script>
my js code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.listen(3308,() =>{
console.log('My server is running');
})
const jsonParser = bodyParser.json();
//
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})

I reproduced your code without any error. To test it quickly, i send the index.html as the default route.
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const port = 3308;
const app = express();
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/index.html'));
});
app.post('/success.html', urlencodedParser, (req, res) => {
res.send(req.body.title);
});
app.listen(port, () => {
console.info(`server running on port ${port}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload Example</title>
</head>
<body>
<form method="POST" action="/success.html">
<div id="input-area">
<textarea
id="title"
name="title"
rows="1"
cols="75"
placeholder="Title"
onkeyup="removedForExample"
></textarea>
<textarea
rows="10"
type="text"
cols="75"
placeholder="Description"
name="description"
></textarea>
<div id="calender"><input id="dater" type="date" value="" /></div>
<button type="submit" value="Submit" id="buton">Add Task</button>
</div>
</form>
</body>
</html>

First of all, I am not sure which version of Express you are using but if you are using version 4.0 or up, you don't really need to import body-parser separately.
Also, you may re-order the code. Why don't you try like this?
const jsonParser = bodyParser.json();
const urlencodedParser = bodyParser.urlencoded({ extended: false })
app.post('/success.html', urlencodedParser , function (req, res) {
console.log(req.body.title);
})
app.listen(3308,() =>{
console.log('My server is running');
})

Related

Can't handle post request

I'm trying to redirect using res.redirect() function. When I submit the form it should insert the data into the database and redirect me to home root. But the later is giving me this error:
Cannot POST /
this is my entire js file
const express =require("express");
const mongoose =require("mongoose");
const app=express();
const path=require("path")
const bodyparser= require("body-parser");
const Blog = require("./model/schema");
const { findById } = require("./model/schema");
app.use(express.static("public"));
app.set("views",path.join(__dirname+"/views"));
app.set("view engine","ejs");
app.use(bodyparser.urlencoded({extended:true}));
mongoose.connect("mongodb://127.0.0.1:27017/blogdb", {useNewUrlParser: true, useUnifiedTopology: true })
.then(()=>
{
console.log("Connection successful!");
})
.catch(err=>
{
console.log("Error: connection failed")
})
app.get("/",async(req,res)=>
{
const blogs=await Blog.find({});
//console.log(blogs);
res.render("blogdata/show",{blogs});
})
app.get("/create",async(req,res)=>
{
// const id=req.params["id"];
// const eblog= await Blog.findById(id);
res.render("blogdata/form");
})
app.post("/create",async(req,res)=>
{
await Blog.insertMany([
{name:req.body.author,blog:req.body.blogcontent}
])
res.redirect("back");
})
app.listen(3000,()=>
{
console.log("Server is up and running");
})
This is all the file I have
enter image description here
HTML form
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/formstyle.css">
<meta charset="utf-8" />
<title>create blog</title>
</head>
<body>
<div><h1><b>Create your own blog!</b></h1></div>
<div class="form">
<form action="/create" method="post">
<div class="name-in">
<label for="name">Author</label>
<br>
<input type="text" id="name" name="author" class="name" value="">
</div >
<div class="text-in">
<label for="para">Enter your blog</label>
<br>
<textarea name="blogcontent" id="para" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="form" id="btn">Submit</button>
<!-- <label for="text">Edit your blog</label>
<input name="text" id="text"
type="text"
class="blog"
value= "" > -->
</form>
</div>
</body>
</html>
Please mention why this is happening and is there any better way to do this?
Well, you have an endpoint /create for the POST method, but the error says that you're trying to send the form to / on POST.
Make sure in your form that you add the correct url (meaning to add /create)

How to upload images on node js?

I am having issues getting any image data on the form in the ejs file after submitting. Upon debugging, there is a req.body.image which has the filename but req.file is undefined. I have tried many sites online detailing how to upload images but none seem to be working, any suggestions?
Part of the code in server.js file:
require("dotenv").config()
const express = require("express");
const cors = require("cors");
const path = require('path')
const app = express();
const mongoose = require("mongoose")
const fs = require('fs')
const multer = require('multer')
const fileupload = require("express-fileupload");
const Grid = require("gridfs-stream");
let gfs;
app.use(fileupload());
require('./routes/auth.routes')(app);
require('./routes/user.routes')(app);
app.use('/uploads', express.static('uploads'))
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
app.use(cors(corsOptions));
app.use(express.json());
var storage = multer.diskStorage({
destination: function(req,file,cb){
cb(null, '../uploads/')
},
filename: function(req, file, cb) {
cb(null, Date.now()+file.originalname)
}
})
const fileFilter = (req,res,cb) =>{
if(file.mimetype === "image/jpeg"||file.mimetype ==='image/png'){
cb(null, true);
}else{
cb(null,false);
}
}
var upload = multer({
storage:storage,
fileFilter: fileFilter
})
app.post('/makepost', upload.single('image'), async function(req, res, next){
if(req.file)
{
const pathName=req.file.path;
res.send(req.file.filename)
}
await db.post.create({
"author": "",
"title": req.body.title,
"img": req.file,
"description": req.body.description
})
res.render('pages/index', {loggedin: loggedin, test: test});
});
createpost.ejs page:
<!DOCTYPE html>
<html lang="en">
<head>
<%- include('../partials/head'); %>
</head>
<body class="u-body u-xl-mode"><div class="u-clearfix u-sheet u-valign-middle u-sheet-1">
<%- include('../partials/navbar', {loggedin:loggedin}); %>
<section>
<h1 align="center">Create post</h1>
</section>
<div class="createpost">
<form action="/makepost" method="post">
<label for="title">
<!-- font awesome icon -->
<i class="fab fa-adversal"></i>
</label>
<input type="text" name="title" placeholder="Title" id="title" required>
<br>
<label for="description">
<i class="fa fa-paper-plane"></i>
</label>
<input type="text" name="description" placeholder="Description" id="description" required>
<br>
<label for="image">Upload Image</label>
<input type="file" id="image" name="image" required>
<input type="submit" value="Upload post">
</form>
</div>
</div>
<footer>
<%- include('../partials/footer'); %>
</footer>
</body>
</html>
Add enctype='multipart/form-data' attr to the form.
Whenever you have files inside a form it is required that you have this.
example:
<form action="/makepost" method="post" enctype="multipart/form-data">
...
</form>

Node.js express: trying to get text from HTML form, req.body empty

I'm trying to build a basic text to speech form, but I cannot grab the text from the form.
I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
</body>
</html>
app.js
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const configRoutes = require("./routes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
configRoutes(app);
app.listen(3000, () => {
console.log("Speech Server");
});
index.js
const express = require("express");
const speakRoutes = require("./speak");
const constructorMethod = (app) => {
app.use("/speak",speakRoutes);
app.use("*", (req,res) => {
res.sendFile("index.html", { root: "./public" });
});
};
module.exports = constructorMethod;
speak.js
const express = require("express");
const router = express.Router();
router.post("/", async (req,res) => {
console.log("POST");
console.log(req.body);
res.sendFile("index.html", { root: "./public" });
});
module.exports = router;
I would greatly appreciate some help! Thank you!
Your input has no name, give your input a name so you know what property to look for in the form:
<input type="text" id="text-box" name="whatever" ... />
EDIT: A client-only example. One field has a name.
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(e.currentTarget).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
<input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
I fixed my own issue! It worked by changing post to get in the route and the html form method, and req.body to req.query

How to fix Cannot PUT /blogs/:id

I am making RESTful BlogApp and PUT method is not working.I only get error saying Cannot PUT /blogs/:id. I don't see what could go wrong. Everything looks fine to me. Please let me know if you find a problem. I know this might be a bad post but it is one of my first posts. Here is what i coded:
<form action="/blogs/<%= blog._id %>?_method=PUT" method="POST" class="ui
form">
<div class="field">
<label for="blog[tittle]">Tittle</label>
<input name="blog[tittle]" type="text" value="<%=
blog.tittle %>">
</div>
<div class="field">
<label for="blog[image]">Image URL</label>
<input name="blog[image]" type="text" value="<%= blog.image
%>">
</div>
<div class="field">
<label for="blog[body]">Content</label>
<textarea name="blog[body]"><%= blog.body %></textarea>
</div>
<button type="submit" class="ui blue button">Save</button>
</form>
const express = require('express');
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const mongoosePassword = 'bm9kZS1yZXN0LWJsb2c=';
mongoose.connect('mongodb://mesopotamija9:' + mongoosePassword + '#node-
rest-blog-shard-00-00-xb2tn.mongodb.net:27017,node-rest-blog-shard-00-01-
xb2tn.mongodb.net:27017,node-rest-blog-shard-00-02-
xb2tn.mongodb.net:27017/test?ssl=true&replicaSet=node-rest-blog-shard-
0&authSource=admin&retryWrites=true', {useNewUrlParser: true});
app.set('view engine', 'ejs')
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
app.put('blogs/:id', function(req, res){
Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err,
updatedBlog){
if (err) {
res.redirect('/blogs');
console.log(err);
} else {
res.redirect('/blogs/' + req.params.id);
console.log(updatedBlog);
}
});
});

node.js express-uploadFile undefined

I'm trying to upload a .txt file with the middleware express-uploadFile. However, when I try to test it my file is undefined.
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var app = express()
app.use(fileUpload());
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/send', function(req, res){
console.log(req.files.UploadBox);
console.log(req.body.Question);
});
<form id="Izone" action="/send/" method="post" encType="multipart/form-data">
<input type="text" name="Question" id="Question" placeholder="Question" autofocus autocomplete="off"><br/><br/>
<label for="UploadBox" id="UploadBoxStyle"> Upload File </label>
<input type="file" name="UploadBox" id="UploadBox">
<input type="submit" name="send" id="send" value="send"/>
</form>
req.body.Question works fine. However, req.files gives me undefined.
I don't know if the issue is bodyParser or fileupload itselft.

Categories

Resources