I have recently started picking up Node.js with the Express framework. I created a simple server and attached an HTML file with a form consisted of a single button of type submit which was supposed to send a post request to the server. It doesn't give me any errors but when I try to log a message to the console upon pressing the submit button, nothing happens. I am pretty sure it has something to do with the HTML form syntax but I can never be too sure. Here is the HTML:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<form class="test" action="http://localhost:8000/example" method="post">
<input type="submit" name="but" value="Press me">
</form>
</body>
</html>
Here is the Express code:
const http = require("http");
const app = require("express")();
const path = require('path');
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/example", (req, res) => {
console.log("pressed");
});
app.listen(8000, ()=>{
console.log("Running at 8000");
});
It's occurs because app.use () is treated as middleware for your application. To work properly you should use app.get (). Here is more detailed explanation. Other alternative is provide your html as an static content, you can see more about here.
To work properly you should change your code to this:
app.get("/", (req, res) => {
res.sendFile(__ dirname + "/index.html");
});
You can also modify your HTML to this:
<form class="test" action="/example" method="post">
Because is in the same host. You just use complete url when performing action to other host.
Change this...
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
to this...
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
Related
In my code below, the middleware is supposed to return the parsed data in console as an object accessed by req.body, but it returns an empty object for some reason.
Code and Console Snapshot1
Code and Console Snapshot2
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const { use } = require('express/lib/application');
/*
ulrEncodedParser middleware is used to invoke below function
to parse posted data to POST functions
var urlEncodedParser = bodyParser.urlencoded({extended : false});
var jsonParser = bodyParser.json();
*/
//set view engine to be able to visit views
app.set('view engine', 'ejs');
//middleware for styles to be loaded on pages when req made by views
app.use('/stylesheets', express.static('stylesheets'));
// middleware to parse application/x-www-form-urlencoded
//app.use(bodyParser.urlencoded({ extended: false }));
// middleware to parse application/json
//app.use(bodyParser.json());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
//GET "/" req, fires up home page
app.get('/', function(req, res){
res.render('home');
});
//GET "/home" req, aslo fires up home page
app.get('/home', function(req, res){
res.render('home');
});
//GET "/signup" req, fires up sign up page
app.get('/signup', function(req, res){
res.render('signup');
});
//POST information enetered on sign up form
app.post('/signup', function(req, res){
console.log(req.body);
//res.render('signup-success', req.body);
});
//server to run on port 3000
app.listen(3000, function(){
console.log('server listening on port 3000');
});
I also tried initialize two separate variables where the functions of urlencoded() and bodyParser.json() can be accessed var for both middlewares instead of using app.use() middleware this way:
var urlEncodedParser = bodyParser.urlencoded({extended : false});
var jsonParser = bodyParser.json();
and then pass in each in the app.post() request routed to the signup page but it still returns the same, empty.
Here is my signup.ejs as well for reference.
<!DOCTYPE html>
<html>
<head>
<link href="/stylesheets/style.css" rel="stylesheet" type="text/css" />
<title>Sign Up Page</title>
</head>
<body>
<h1>Sign Up</h1>
<h3>Enter the requested information below for your user profile to be created.</h3><br>
<form id="signup-form" action="/signup" method="post">
<label for="firstName">First Name</label><br>
<input type="text" id="firstName" placeholder="first name"><br><br>
<label for="musicPreferences">Music Prefrences</label><br>
<input type="text" id="musicPrefrence" placeholder="music preferences"><br><br>
<label for="favoriteArtists">Favorite Artists</label<br>
<input type="text" id="favoriteArtists" placeholder="favorite artists"><br><br>
<label for="pastConcerts">Past Concerts Attended</label><br>
<input type="text" id="pastConcerts" placeholder="concerts attended"><br><br>
<label for="futureConcerts">Fututre Concerts Want to Attend</label><br>
<input type="text" id="futureConcerts" placeholder="future concerts"><br><br>
<input type="submit" value="submit"><br>
<%- include('partials/nav.ejs') %>
</form>
</body>
</html>
Sign up Page UI
Any help is appreciated!
The backend works correctly because when sending a request with curl, body is shown in the console. It seems the client sends the request incorrectly.
screenshot
Been using mongoDB with the mongoose ODM and I can't seem to figure it out. I've been following a tutorial online, but when I test out my code, it gets redirected to an empty page that says "Cannot POST /"
Here is my code:
server.js
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var PORT = 3332;
app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/gamedata", {
useNewUrlParser: true
});
var gameSchema = new mongoose.Schema({
nickname: String
});
var User = mongoose.model("User", gameSchema);
app.post("/addname", (req, res) =>{
var playerNickname = new User(req.body);
playerNickname.save()
.then(item => {
console.log("nickname created")
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
console.log("error baby!");
});
});
app.listen(PORT, function () {
console.log("server is up and running using port " + PORT)
});
index.html
<html>
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
<body>
<h1 class="center-align">Create Nickname</h1>
<form method="post" name="/addname">
<input id="pickName" type='text' name='pickName' placeholder='Nickname' required>
<input id='ready' value=" Ready >" type='submit'>
</form>
</body>
<script>
</script>
</html>
What seems to fix it is when i change
app.use("/", express.static(__dirname));
to the following code:
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
But in my specific case i cannot do this.
Does anyone know of a work around?
You should change your index.html
Insteady of use:
<form method="post" name="/addname">
you should use:
<form method="post" action="/addname">
This should solve your problem.
The Action Attribute
The action attribute defines the action to be performed when the form is submitted.
Usually, the form data is sent to a page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server called "/addname". This page contains a script that handles the form data:
If the action attribute is omitted, the action is set to the current page.
The attribute "name" is used in input fields, not in the tag.
I just found some information here.
https://www.w3schools.com/html/html_forms.asp
I've tried numerous methods to solve this from app.use(express.static(__dirname + "public")) to res.render and it works in my terminal but not in my local host. Where am I going wrong?
Here's my JS file:
const express = require('express');
const bodyParser = require('body-parser');
var fs = require ('fs');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
//
app.get('/index', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
//app.use(express.static(__dirname + '/public'));
//app.get('/index.html', (request, response) => response.sendFile( __dirname, "/index.html"));
app.post('/userinfo', (request, response) => {
const postBody = request.body;
console.log(postBody);
response.send(postBody);
});
app.listen(3002, () => console.info('Application running on port 3002'));
And here's my HTML file:
<!-- index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Express - Node.js POST data example</title>
</head>
<body>
<form action="/userinfo" method="POST">
Some data: <input type="text" name="data" id="data">
<button type="submit">Send</button>
</form>
</body>
</html>
There is no response for base url or / route is defined. You have defined only two routes and I assume /index for your index page. So, the page will be render at localhost:3002/index . You have to define another response for / or base url like,
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
Hopefully, your problem will be solved.
I want to save the data submitted by the user through a form using post method and then redirect it to another html page that I have on my local machine, is there any way to achieve this using Node.js or express how do I do that?
Here is the html code for form:
<html>
<head></head>
<body>
<form action="post_register.html" method="POST">
university name:<input type="text" name="name" placeholder="University name"><br>
faculty Username:<input type="text" name="facul" placeholder="faculty username"><br>
password:<input type="password" name="password" placeholder="password"><br>
<button >register</button>
</form>
</body>
and here is the javascript file:
var express = require("express");
var app = express();
var bodyparser=require("body-parser");
app.use(bodyparser.urlencoded({ extended: true }));
app.listen(3000);
app.get("/domain_register",function(req,res)
{
res.sendFile(__dirname+"/domain_register.html");
})
app.post("/post_register",function(req,res)
{
console.log(req.body);
res.end("yes");
});
all I want is that after pressing submit button the data is received and the user is redirected to post_register.html file.
I tested below code in my computer and it worked. I added res.redirect('/success') line to the post request handler and created an handler for /success path:
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
You can change /success path with your naming choice.
App.js
var express = require('express')
var app = express()
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({ extended: true }))
app.listen(3000)
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html')
})
app.get('/success', function (req, res) {
res.sendFile(__dirname + '/success.html')
})
app.post('/register', function (req, res) {
console.log(req.body)
res.redirect('/success')
})
index.html
<html>
<head></head>
<body>
<form method="post" action="/register">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
success.html
<html>
<head></head>
<body>
<h1>Welcome</h1>
</body>
</html>
I stuck in figuring out how client file find routes function in express. My app structure is like that,
|-root
|--public
|---files
|---scripts
|---css
|--views
...
The client side html is as blow, which is in /public/files. It can be rendered to http://localhost:3000/files/like_animal.html correctly.
<html>
<body>
<form action="/handleForm" method="post">
name: <input name="usename"><br>
I like <input name="animal"><br>
<input type="submit" value="Go">
</form>
</body>
</html>
The js file is like that,
var express = require('express');
var app = express();
var path = require('path');
app.use(express.static(path.join(__dirname + 'public')));
console.log('start');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/handleForm', (req, res) => {
var name = req.body.name;
var animal = req.body.animal;
console.log(name + " " + animal);
res.send('Thank you');
});
app.listen(3000, () => {
console.log('Listening on port 3000');
});
Now I am not sure where I should put this js file in. I tried to put it in /public/scripts or root, even also in /public/files. But nothing works. Every time I submit the form, the browser always show Cannot POST /handleForm. As a one-week newbie in express, I am totally lost. Any hint will be appreciated. Thanks a lot.
You should put your script at the root then specify the public's path like this.
app.use(express.static(path.join(__dirname, 'public')));
Another note, app.use is used to make a middleware. You should define your route using app.post.
app.post('/handleForm', (req, res) => {
// ...
});