How to send JSON as respond from Node js to Html file - javascript

I'm trying to send JSON from Node js to html file as a response, but after I submit HTML form disapears and this shows up Respond after I submit a form. I tried ajax but it doesn't work beacuse I get redirected to this (image above). I'm trying to make a simple login form and if user inputs nothing then message should get displayed saying "Nothing was input" below the form.
JS code (node.js, express framework)
app.get('/login', function(req, res){
res.sendFile(path.join(__dirname+'/Frontend/html/login.html'));
});
app.post('/login', function(req, res){
res.json({a: 5});
});
html code
<form method="POST">
<input type = "text" name = "username" id = "username" placeholder="Username">
<input type = "password" name = "password" id = "password" placeholder="Password">
<button id = "gumb" type = "submit">Prijavi se</button>
</form>
<p id = "demo"></p>
<script>
document.getElementById('gumb').addEventListener('click', function(){
const xhr = new XMLHttpRequest();
console.log("test");
if(xhr.readyState == 4 && xhr.status == 200){
document.write(xhr.responseText);
}
else{
console.log("broke");
}
xhr.open('get', 'http://localhost:8000/login', true);
});
</script>

Your code works as expected, you just send a json key-value pair to your frontend, when the route is invoked. The data is shown in your browser.
app.post('/login', function(req, res){
res.json({a: 5});
});
Usually, you would want to do something with the data sent to your backend:
app.post('/login', function(req, res){
user= req.body.username;
password = req.body.password;
console.log(`User: ${user} is requesting login`);
// do something with the data - login, save, edit
res.end();
});
Since you obviously commit login data (FROM a form TO your backend),
you should use some authentification middleware to perform a login.
To comfortably send processed html to your backend, you should get acquainted with the subject of views.
And the express api documentation will be very useful to you, I'm sure. ;)
https://expressjs.com/en/api.html

Related

Show new html page after post request?

1. Summarize the problem
First I want to describe, how the project should work. I want to build my own little website with html, css, javascript (and expressJS and nodeJS). I´ve also watched a few tutorials about Rest-APIs and how they work. I want to create a login page, where you should enter a password to get to the "main- page".
The problem is, that I´m working with a post-request atfer the user has clicked on a "submit" - button, where the value of a password box will be send to a server to check. After this was executed, I dont know how to show the new html page and how to redirect the user to a new page.
2. Describe what you´ve tried & 3. Show some code
I´ve tried two different things. Here is my beginning of the code in my server.js:
var app = express();
var server = app.listen(3000);
app.use(express.static('website'));
First I wanted to send a file after checking the password in my post request:
app.post('/all', function(req, res) {
if(req.body.password != 'example') {
return
}
res.sendFile('index.html');
});
I found this github issue, where a user has the same problem: https://github.com/expressjs/express/issues/692
But this method doesnt seem to work in a post-request. So I´ve tried another thing. I already knew, that sendFile() works in a get-request (as I mentioned in a github issue), so I´ve made this:
app.get('/all', function(req, res) {
res.sendFile('index.html');
});
app.post('/register', function(req, res) {
if(req.body.password != 'example') {
return
}
res.redirect('/all')
});
For this code example I used the following stack overflow page: How to redirect to another page after serving a post request in Node.js? but it didnt work either.
3. Show some code:
Script in html doc :
function XHTML_POST(path, parms, callback) {
req = new XMLHttpRequest();
var ret = false;
callbackPOST = callback;
req.open("POST", path, true);
req.onload = function () {
if (req.status != 200 && req.status != 1223 && req.status != 0 && req.status != 204) {
if (req.status == 401) { }
else { }
}
else {
callbackPOST = callback;
}
}
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
req.setRequestHeader("Cache-Control", "no-cache");
req.send(parms);
}
function postPass() {
var pass = document.getElementById('pwBox').value; //id of passwordbox
XHTML_POST('/register', 'password=' + pass, callback)
}
function callback() { }
</script>
After clicking on a submit button the postPass() function will be executed. Hopefully you understood my problem and what I´m trying to make. Thanks for reading it.
You can use the html forms :
HTML :
<form method="POST">
<input type="email" name="youremail" placeholder="Email Address" required>
<input type="text" name="yourname" placeholder="Name" required>
<input class="subscribe-button" type="submit" value="Subscribe">
</form>
NodeJs Server :
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, 'login.html'))
})
app.post("/", (req, res) => {
//Your Password Verification
if(true){
res.sendFile(path.join(__dirname, 'index.html'))
}else{
res.sendFile(path.join(__dirname, 'login.html'))
}
})

formdata object is empty for html form post request

I'm trying to use formdata object to send form data to my server. I need this because one of my input fields is a file. However the formdata object is blank when I try to send the data to my server, it also prints out "{}". What is the issue? I have jquery updated to 11.1 which supports formdata. Thanks.
<form enctype="multipart/form-data" name="formName" id="formId">
<input type="text" name="name" class="form-control" id="name">
</form>
<button type="submit" class="btn btn-xl sub">Send Message</button>
<script>
$(".sub").click(function(){
var formElement = document.querySelector("form");
alert(formElement); //alert message is "[object HTMLFormElement]"
var d = new FormData(formElement);
alert(JSON.stringify(d)); //alert message is "{}"
$.post("/email",d,function(data){
alert("success!");
});
});
</script>
Server:
/*never reaches endpoint*/
app.post('/email', function(req, res) {
console.log("entered");
console.log(req.body) // form fields
console.log(req.files) // form files
var resume = req.files;
email(req.body, resume);
});
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
How are you parsing the body of POST requests on your node server?
The issue is that FormData will set the content type to be multipart/form-data, which Express' body-parser doesn't understand.
Note the comment here:
[body-parser] does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: busboy and connect-busboy; multiparty and connect-multiparty; formidable; multer.
So in other words, you have to user a different module to handle the multipart body that FormData sends. I can recommend formidable, in which case you're server code would look something like:
const formidable = require('formidable')
exports.createPost = (req, res, next) => {
var form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
console.log(fields)
res.send('NOT IMPLEMENTED: pollsController createPost');
}
}

How to receive POST form data in node.js from client

Hello guys i am a newbie when it comes with web development, especially working with node.js, i want to find out how i can receive data sent from client via ajax Post.
below is the script i wrote to post the form data
<script type="text/javascript">
function ecoachSignIn(){
var user = $('#user').val();
var password = $('#pass').val();
var SignIn ={
user : $('#user').val();
pass : $('#pass').val();
};
$.ajax({
type:'POST',
url: 'https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user='+username+'&pass='+password,
data: {
user : $('#user').val();
pass : $('#pass').val();
},
success: function(creditials){
}
});
alert("Hello! your username is "+username+" and password is "+password);
}
this is the form itself
<form style="margin-top:25%; margin-left:30%" method="post" action='/'>
<input class="input" type="text" id="user" required="true" name="username" placeholder="Username">
<input class="button-1" style="background:#000" onClick="ecoachSignIn()" type="submit" value="Log in">
<div style="margin-top:10px">
<input class="input" type="password" id="pass" name="password" required="true" placeholder="Password">
</div>
</form>
node.js server code
router.post('/', function(req, res) {
var request = require("request"),
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
url = req.query.url;//trying to get the url in my jQuery at client side but not working
console.log("Username = "+user_name+", password is "+password);
request.get(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
if (!error && response.statusCode == 200) {
var json_body = JSON.parse(body);
console.log(json_body);
status = json_body.status;
success = json_body.msg;
fname = json_body.profile.fname;
console.log("hi "+fname); // Print the username.
console.log("status is "+status); // Print the status.
console.log("success is "+success); // Print the success.
}
}
);
res.end("yes");
});
My major problem is how to process this in node.js backend server
Hope my question is clear ....thanks
Your server side code:
user_name=req.body.username,//this picks the username frome the form directly not from the javascript i created to post the data
password=req.body.password,//same problem with the username
Your client side code:
user : $('#user').val();
pass : $('#pass').val();
You call the fields user and pass on the client but username and password on the server. You have to use the same name in both places.
It works when you use the form normally because the name attributes match the names you use the on server.

Passing a JSON object from clientside JavaScript to NodeJS

I have a webpage which creates a JSON object based on user input. I would like to then somehow allow the user to submit this JSON object to a NodeJS script for processing/insertion into a MySQL database. However, I'm really not sure how to do something like this -- the best I can come up with is some form of a POST, but I'm not sure where to start with this.
Because I don't know what such a method would be described as, I haven't had much success in locating any tutorials or other resources online.
Could anyone suggest some articles or documentation to look at that would be relevant to something like this? Or, at least, tell me what to search for? Thanks.
EDIT: This is the code I am trying to get working at the moment. I'm just trying to convert the POST data type from string to JSON on both sides.
Serverside:
var express = require('express');
var fs = require('fs');
var app = express();
app.use(express.bodyParser());
app.get('/', function(req, res){
console.log('GET /')
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('thanks');
});
port = 8080;
app.listen(port);
console.log('Listening at http://localhost:' + port)
Clientside:
<html>
<body>
<form method="post" action="http://localhost:8080">
Name: <input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
<script type="text/JavaScript">
console.log('begin');
var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "http://localhost:8080", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-length", params.length);
//http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
console.log('onreadystatechange');
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
else {
console.log('readyState=' + http.readyState + ', status: ' + http.status);
}
}
console.log('sending...')
http.send(params);
console.log('end');
</script>
</body>
</html>
Here is a very basic example using jQuery to do the post request and an express app. I think it should be a decent starting point.
// client side, passing data to the server
$.post("/foo/", { data : { foo : "bar" } }, function(temp) {
// temp === "I am done";
});
// serverside app.js
var express = require("express");
var app = express();
// will parse incoming JSON data and convert it into an object literal for you
app.use(express.json());
app.use(express.urlencoded());
app.post("/foo/", function(req, res) {
// each key in req.body will match the keys in the data object that you passed in
var myObject = req.body.data;
// myObject.foo === "bar"
res.send("I am done");
});
EDIT: JSON.stringify() and JSON.parse() will serialize/deserialize JSON. (jQuery makes this much easier, but if you wanna go pure javascript)
Change to var params = "text=" + JSON.stringify({ foo : "bar" });
and
console.dir(JSON.parse(req.body.text));
It worked for me on my local.

POST Request Issue in ExpressJS

I'm working with NodeJS and I'm working on letting users upload files. Right now though I'm having a lot of problem even trying to get a simple POST request.
Over in my index.ejs file I have some code that creates a form and then sends a post request:
<div id="uploaddiv">Upload things here<br>
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="text" name="title"><br>
<input type="file" name="upload" multiple="multiple"><br>
<input type="submit" value="Upload">
</form>
</div>
Then in server.js, I have code that handles the uploading.
var server = express.createServer();
//bunch of stuff left out
server.get('/upload', function(req, res) {
console.log("uploading!");
if (req.method.toLowerCase() == 'post') {
res.write('lol');
}
});
My problem is that navigating directly to localhost/upload will console.log properly, but clicking on the button gives me the error "Cannot POST /upload".
Thanks!
server.get means handle an HTTP GET. You want server.post. FYI the "Cannot XXX /uri" error is what express responds with when no active route matches the request and no 404 error handler has been configured.
By using server.get(), you're instructing that route to only respond to GET requests, but the form is obviously a POST.
You should use server.post().
You can also use server.any() if you want to it respond to both GET and POST (and every other HTTP verb as well).
You should probably use Felix Geisendörfer's node-formidable to upload files.
var express = require('express'),
app = express.createServer(),
util = require('util'),
formidable = require('formidable');
app.get('/upload', function (req, res){
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>');
});
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = '.';
form.keepExtensions = true;
form.parse(req, function(err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
});
app.listen(3000, '127.0.0.1');
It is just a simple as this to do file uploading thanks to node-formidable.

Categories