How to fix Cannot PUT /blogs/:id - javascript

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);
}
});
});

Related

What is causing the type error in my code?

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error
TypeError: Cannot read properties of undefined (reading 'fName')
Kindly let me know the error in my code.
<form action="/" method="POST">
<img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
<h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
<div class="form-floating">
<input type="text" name="fName" class="form-control top" placeholder="First Name">
</div>
<div class="form-floating">
<input type="text" name="lName" class="form-control middle" placeholder="Last Name">
</div>
<div class="form-floating">
<input type="email" name="email" class="form-control bottom" placeholder="name#example.com">
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
<p class="mt-5 mb-3 text-muted">Follow me</p>
</form>
// const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
});
app.post("/", function(res, req){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
app.listen(3000, function() {
console.log("Server is running on Port 3000");
}); ```
I found these errors in your code, check them and it will work fine.
app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).
app.post("/", function(req, res, next){
var firstName = req.body.fName;
var middleName = req.body.lName;
var eMail = req.body.email;
console.log(firstName, middleName, eMail);
});
Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object.
But in your case you are reading it from response object but it should be from request.
Thanks

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>

express post method and body.req does not work

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');
})

Cannot access req.body, even when using body-parser

I am trying to get my login functionality up and running, but i am unable to access the req.body object.
When i first encountered the issue, the post route was not even getting triggered (console.log was not showing at all in terminal) and the request would eventually time out. This stopped after i added this line in the body-parser initialization:
type: 'x-www-form-urlencoded',
Now, the console.log form the route appears in the terminal, but both parameters are empty.
Router.js
const express = require('express'),
router = express.Router();
router.post('/signup', function (req, res) {
console.log(req.body.name, req.body.password);
res.send('posted');
});
module.exports = router;
app.js
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
http_port = process.env.HTTP_PORT;
const http = require('http').createServer(app);
app.use(express.static(path.join(__dirname, 'public')));
app.use(
express.urlencoded({
type: 'x-www-form-urlencoded',
extended: true,
})
);
app.use(express.json());
app.use(cookieParser());
app.use(require('./backend/router'));
http.listen(process.env.PORT || http_port, () =>
console.log(`App listening on port ${http_port}`)
);
Form from index.html
<div>
<form method="POST" enctype="application/x-www-form-urlencoded">
<div class="row">
<label>Full Name</label>
<input
name="name"
type="text"
required
placeholder="Enter your name"
/>
</div>
<div class="row">
<label>Email</label>
<input
name="email"
type="email"
required
placeholder="Enter your email"
/>
</div>
<div class="row">
<label>Password</label>
<input
name="password"
type="password"
required
placeholder="Enter your password"
/>
</div>
<div class="row">
<label>Confirm Password</label>
<input
name="password_confirm"
type="password"
required
placeholder="Confirm your password"
/>
</div>
<div id="button" class="row">
<button
formmethod="POST"
formenctype="application/x-www-form-urlencoded"
type="submit"
>
Sign Up
</button>
</div>
</form>
</div>
I was not able to fix it, but i managed to find a workaroud. The info from the form is also in request.fields, so i am going to use that instead of request.body. I still would like to know why it doesn't work as normal though.
Remove type: 'x-www-form-urlencoded' in your parser and add action="http://localhost:3000/signup" to your form
Perhaps try
app.use(bodyParser.json());
instead of
app.use(express.json());

Why can't I successfully to fetch url from form and thus attribute it to the source(src) of images?

I've having an issue I shouldn't be having with my Node/Express code(s). I can't for the life of me get the image source (src) attribute to work, hence the images added from a form aren't being displayed. It just displays as unknown. I have no idea where I'm going wrong, and have gone through the whole code(s) multiple times, but nothing seems out of place.
The JS code is as follows:
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/yelpcamp");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
//Camp Schema
var campgroundSchema = new mongoose.Schema({
name: String,
image: String
});
var Campground = mongoose.model("Campground", campgroundSchema);
app.get("/", function(req, res) {
res.render("landing");
});
app.get("/campgrounds", function(req, res){
Campground.find({}, function(err, sites) {
if(err) {
console.log(err);
}
else {
res.render("campgrounds", {
campgrounds:sites
});
}
});
});
app.post("/campgrounds", function(req, res){
//Fetching data from form
var name = req.body.campName;
var url = req.body.imageUrl;
var newCamp = {
name: name,
image: url
};
//New Campground and Save to DB
Campground.create(newCamp, function(err, campground) {
if(err) {
console.log(err);
}
else {
//Redirect to Camp Page
console.log(campground);
res.redirect("/campgrounds");
}
});
});
app.get("/campgrounds/new", function(req, res){
res.render("new");
});
app.listen(4500, function(){
console.log("Yelp Camp Server Started!!!");
});
The following are the relevant EJS codes:
Form EJS
<div class="container">
<form action="/campgrounds" method="POST">
<label for="campName">Name</label>
<input type="text" id="campName" name="campName" placeholder="Add Campground Name">
<label for="campImage">Image</label>
<input type="url" id="campImage" name="imageUrl" placeholder="Add Image Url">
<input type="submit" name="submit" value="Add Campground">
</form>
Go Back
</div>
Add Image EJS
<div class="container">
<h1 style="margin-top: 8%;">Campgrounds Presentation</h1>
<div class="row">
<% campgrounds.forEach(function(campground) { %>
<div class="col-md-4 col-sm-6 col-xs-12">
<div class="thumbnail">
<img src="<%= campground.image %>">
<h3 class=text-center><%= campground.name %></h3>
</div>
</div>
<% }); %>
</div>
</div>

Categories

Resources