Why doesn't post won't save to page when refreshing? - javascript

Using Javascript, NodeJS, MongoDB, Express
In my app a user is suppose to type in the input field and when they click the submit button the text gets appended to the page. I am able to successfully post text to the page but when I refresh my browser, my post do not show up. I think I need to do a get request through ajax in the script section of my partials/test.ejs, but I am unsure how to execute this.
models/Blog.js
var
mongoose = require('mongoose'),
Schema = mongoose.Schema,
BlogSchema = new Schema({
name: String
})
var Blog = mongoose.model('Blog', BlogSchema)
module.exports = Blog
views/partials/test.ejs
<body>
<form>
<button type="submit" class="btn btn-default pull-right" id="create">Submit</button>
</form>
<div class="feedback-messages"></div>
</body>
<script type="text/javascript">
var messages = $('.feedback-messages')
var postItem = $("#create")
postItem.on('click', function(evt) {
evt.preventDefault();
$.ajax({
url: '/test',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({data: newItem})
})
.done(function(data) {
console.log("Hello");
messages.append(newItem)
})
routes/index.js
var
express = require('express');
router = express.Router();
bodyParser = require('body-parser');
mongoose = require('mongoose');
Blog = require('../models/Blog.js');
// route for home page
router.get('/', function(req, res) {
res.render('./partials/home');
});
//route for test page
router.get('/test', function(req, res) {
res.render('./partials/test');
});
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false}));
router.get('/test', function(req, res){
Blog.find({}, function(err, blog){
if(err) return console.log(err)
res.json(blog);
})
});
router.post('/test', function(req, res){
// console.log(req.body)
Blog.create({content: req.body.data}, function(err, item){
if(err) return console.log(err)
res.json({serverSays: "Request received. Added item.", item: item})
})
})
module.exports = router;

try changing you code for saving into this
Blog.create({content: req.body.data})
.then(function(item){
res.json({serverSays: "Request received. Added item.", item: item})
})
.catch(function(err) {
return console.log(err)
})

Related

why my form data doesn't stored in database?

My app.js entire codes:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
app.post("/addname", (req, res) => {
});
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
})
});
This is my index.html file
<!DOCTYPE html>
<html>
<head>
<title>Intro to Node and MongoDB
</title>
</head>
<body>
<h1>Into to Node and MongoDB</h1>
<form method="post" action="/addname">
<label>Enter Your Name</label><br>
<input type="text" name="firstName" placeholder="Enter first name..." required>
<input type="text" name="lastName" placeholder="Enter last name..." required>
<input type="submit" value="Add Name">
</form>
</body>
<html>
After writing my code I open my mongod server than start mongo in other terminal then I run my app.js it worked properly it create server localhost:3000 then I went to my host I add my name in form and then submit, but it doesn't add to my database
Why this is not working?
My form data doesn't stored in my mongodb database. Please help me!
I think the body-parser library is deprecated on express 4 and later versions.
please use
app.use(express.json())
instead of body=parser.
not need to call any npm packages for parsing data from the form.
Here is the issue:
var myData = new User(req.body.firstName, req.body.lastName);
you have to pass an object to new User
var myData = new User( { firstName:req.body.firstName, lastName:req.body.lastName } );
i think i know what is wrong.
change app.use("/"... to app.get("/"...
bacause use handles all requests including POST. so when you send any request it sends the html file again and kills any other process.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
I think you are not passing data correctly in the user model.
app.post("/addname", (req, res) => {
// make sure your request object is getting the same properties
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
As you updated the code for form, lastName is the fieldName. You should make the changes in the schema object too.
Also, Please check the request headers that comes in if it is of Accept:multipart/form-data then the bodyParser won't work instead you should use multer.
Some useful body parsers that you might need to consider if needed.
form-data: multer
x-www-form-urlencoded: express.urlencoded()
raw: express.raw()
json: express.json()
text: express.text()
Updated app.js file:
var express = require("express");
var app = express();
var port = 3000;
app.listen(port, () => {
console.log("Server listening on port " + port);
});
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/node-demo", { useNewUrlParser: true, useUnifiedTopology: true });
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
var nameSchema = new mongoose.Schema({
firstName: String,
lastName: String
});
var User = mongoose.model("User", nameSchema);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addname", (req, res) => {
var myData = new User(req.body.firstName, req.body.lastName);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
Note: you have added two extra routes with same route handler, I have just removed it. Update this file in your project and run it.

Why does my text not showing up after a post request - MongoDB

I am currently making a basic twitter clone. Everything went perfect before my text started not showing up when I made a post request.
What would be the problem?
My code:
app.js:
var express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
ejs = require("ejs");
var app = express();
mongoose.connect("mongodb://localhost:27017/twitter_clone", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("CONNECTED TO DB"))
.catch((error) => console.log(error.message));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));
app.set("view engine", "ejs");
// MONGODB TWEETS SCHEMA
var tweetsSchema = new mongoose.Schema({
text: String
})
var Tweets = mongoose.model("Tweets", tweetsSchema);
//================
//RESTFUL ROUTES
//================
// INDEX ROUTES
app.get("/", function(req, res){
Tweets.find({}, function(err, allTweets){
if(err){
console.log(err);
} else {
res.render("home", {newtweet:allTweets});
}
})
})
app.get("/explore", function(req, res){
res.render("explore");
})
app.get("/notifications", function(req, res){
res.render("notifications");
})
app.get("/messages", function(req, res){
res.render("messages");
})
app.get("/bookmarks", function(req, res){
res.render("bookmarks");
})
app.get("/lists", function(req, res){
res.render("lists");
})
app.get("/profile", function(req, res){
res.render("profile");
})
app.get("/more", function(req, res){
res.render("more");
})
// NEW ROUTES
app.get("/tweet/new", function(req, res){
res.render("new");
})
// POST
app.post("/posttweet", function(req, res){
var text = req.body.text;
var newtweet = {text: text};
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})
//DELETE
app.get("/delete/:id", function(req,res){
mongoose.model("Tweets").remove({_id:req.params.id}, function(err, delData){
res.redirect("/");
})
})
app.listen(5000, function(){
console.log("Server listening on port 5000");
})
home.ejs:
<form action="/tweet/new">
<input class="bluebutton" type="submit" value="Tweet" />
</form>
<div class="tweets">
<% newtweet.forEach(function(newtweet){ %>
<div class="showtweets">
<p class="tweetcontent">
<%= newtweet.text %>
</p>
</div>
<% }) %>
</div>
I asked a similar question before and I found a solution and it worked well for a while, but I made some changes and now it's not working poroperly.
Create a form that sends a post request to "/posttweet":
<form action="/posttweet" method="post">
<input type="text" name="text" />
<input type="submit" value="Tweet" />
</form>
This should make the right request to your single post route.
Edit
Tip: Make sure to send back some response from your handlers, even if its an error, otherwise your server will just hang.

MongoDB not saving data anywhere

I am new in nodejs, mongoose, express and I am trying to create a basic twitter clone. When I want to create a new tweet and hit the submit button nothing happens.
Here is my code:
app.js
var express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
ejs = require("ejs");
var app = express();
mongoose.connect("mongodb://localhost:27017/twitter_clone", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("CONNECTED TO DB"))
.catch((error) => console.log(error.message));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));
app.set("view engine", "ejs");
// MONGODB TWEETS SCHEMA
var tweetsSchema = new mongoose.Schema({
text: String
})
var Tweets = mongoose.model("Tweets", tweetsSchema);
//================
//RESTFUL ROUTES
//================
// INDEX ROUTES
app.get("/", function(req, res){
Tweets.find({}, function(err, allTweets){
if(err){
console.log(err);
} else {
res.render("home", {newtweet:allTweets});
}
})
})
app.get("/explore", function(req, res){
res.render("explore");
})
app.get("/notifications", function(req, res){
res.render("notifications");
})
app.get("/messages", function(req, res){
res.render("messages");
})
app.get("/bookmarks", function(req, res){
res.render("bookmarks");
})
app.get("/lists", function(req, res){
res.render("lists");
})
app.get("/profile", function(req, res){
res.render("profile");
})
app.get("/more", function(req, res){
res.render("more");
})
// NEW ROUTES
app.get("/tweet/new", function(req, res){
res.render("new");
})
// POST
app.post("/posttweet", function(req, res){
var text = req.body;
var newtweet = {textmessage: text};
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})
app.listen(5000, function(){
console.log("Server listening on port 5000");
})
home.ejs:
<div class="middlewelcome">
<h3>Welcome to twitter!</h3>
<p id="welcomingp">This is the best place to see what’s happening in your world. Find some people and topics <br> to follow now.</p>
<button id="getstarted" class="bluebutton">Get Started</button>
</div>
<div class="tweets">
<% newtweet.forEach(function(newtweet){ %>
<div class="showtweets">
<h1>
<%= newtweet.text %>
</h1>
</div>
<% }) %>
</div>
</div>
I tried to manually save a new text previously and it's working fine, so I don't know what would be a problem and why my post route not working
IntweetsSchema the text field is named text but in your POST route you call it textmessage. Try renaming the value in the POST route to match the schema.
app.post("/posttweet", function(req, res){
var text = req.body;
var newtweet = {text: text}; // typo error
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})
schema you defined and object you are passing are not matching

Redirect to another url after post request (AJAX, EXPRESS)

As a part of learning node.js servers I'm working on a little log-in website. There's a site you can open and enter your username which will then be sent through an ajax post request to the server and saved into an array of all users. I wanna make it so that after you submit your username, you will be redirected to another page, unique for every username, where you will be able to see the information about you username. Sort of a 'manage your account' site.
However, I can't seem to figure out a way to redirect me to this page after I have submitted an username.
Say for example you submit a username 'kokot' and it's the 3rd username that's been submitted so far. Thus, in the 'players' array, your user object will look something like this {id: 2, username: 'kokot'}.
Now I want to redirect you to the url localhost:2000/players/2 to see the info about your specific username.
NODE JS
const express = require('express');
const server = express();
const bodyParser = require('body-parser');
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
let players = [];
//loads the home page
server.get('/', (req, res) =>{
res.sendFile(__dirname + '/home.html');
});
//loads the page with the list of players
server.get('/players', (req, res) =>{
res.send(players);
});
server.get('/player/:id', (req, res) =>{
res.send(players[req.params.id]);
});
//takes a new username and saves it to players array
server.post('/', (req, res) =>{
console.log('NEW PLAYER: ' + req.body.username);
players.push({
id: players.length,
username: req.body.username
});
});
/////////////////////////////////////////////////////////////////////////////
server.listen(2000, () => console.log('LISTENING ON PORT 2000'));
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Home</title>
</head>
<body>
<h1>PISKVOREC</h1>
<form id="userForm">
username
<input type="text" name="text" id="userFormInput">
<input type="submit" name="Submit" id="userFormSubmit">
</form>
<script>
$(document).ready(()=>{
let homeUrl = 'http://localhost:2000';
let $userForm = $('#userForm');
let $userFormSubmit = $('#userFormSubmit');
//submits a new username to the server
$userFormSubmit.click(() =>{
$.post(homeUrl, {
username: $('#userFormInput').val()
}, function(){
console.log('USERNAME SUBMITTED TO SERVER');
});
$.
});
////////////////////
});
</script>
</body>
</html>
Thank you for you responses and ideas
Have a nice day
Sure, see below:
server.post('/', (req, res) =>{
console.log('NEW PLAYER: ' + req.body.username);
players.push({
id: players.length,
username: req.body.username
});
res.redirect(`/player/${req.body.username}`);
});
UPDATE
Demo with vanilla Express.js app
app.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
app.post('/this', (req, res, next) => {
res.redirect(`/that/${req.body.username}`);
});
app.get('/that/:id', (req, res, next) => {
res.send(req.params);
});
module.exports = app;
index.hbs
<form method="post" action="/this">
<input id="username" name="username" value="vader" type="text" />
<button type="submit">Submit</button>
</form>
results in a redirect to: http://localhost:3000/that/vader

accessing post data on node server?

I'm trying to send simple form data to a node/express server using AJAX. When submit, I'm brought to a Cannot POST / page and while I'm able to console.log a req, it doesn't include the data from the form. What am I missing?
Form
<form method="POST" class="form-group">
<label for="sentenceCount">Sentences</label>
<input type="number" placeholder="10" name="sentence count" id="sentenceCount" class="form-control parameters">
<button type="submit" id="submit" class="btn btn-primary mt-1">Submit</button>
</form>
AJAX Request
$('button').on('click', function(data) {
$.ajax({
data: data,
url: '/data',
type: "POST"
})
}
)
Server.js
var express = require('express');
var app = express();
app.listen(8000)
app.get('/', function (req, res) {
res.sendFile('/Index.html', {
root: __dirname
})
});
app.post('/data', function (req, res) {
console.log(req)
})
Update:
I've fiddled around and have be able to access a body property but the body is empty and cannot get the input values I need.
AJAX:
$('button').on('click', function(data) {
var formData = $('input').val();
console.log(formData)
$.ajax({
data: formData,
url: '/data',
type: "post"
})
}
)
Server:
app.get('/', function (req, res) {
res.sendFile('/Index.html', {
root: __dirname
})
});
app.use(bodyParser.json())
app.post('/data', function(req, res) {
console.log(req.body)
});
You forgot body parser.
Install body-parser package npm i body-parser
Add body parser JSON middleware before express routes.
Example:
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json())
app.post('/data', (req, res) => {
console.log(req.body);
res.end();
});
And form data should be an object encoded with JSON:
$('button').on('click', function(data) {
var formData = $('input').val();
$.ajax({
data: {value: formData},
url: '/data',
type: "post"
})
}
)

Categories