I think I'm lacking some understanding of these fundamental concepts (I've read a decent amount of resources and examples) of how these functions work server-side and how the html interacts with them. I was writing methods earlier today and communicating between the server and html perfectly, manipulating an array I had stored locally on the server file. For reference I'll show you how I was doing it.
jQuery script in html file:
$.post("/deck", { name: "Angel of Fury", power: 666 }, function(){
});
server file:
var express = require('express'),
app = express(),
db = require('./db'),
bodyParser = require('body-parser'),
controller = require('./controller');
//add body parser middleware
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
//Serves static pages
app.use(express.static(__dirname + ('/')));
//loads the html page
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
var server = app.listen(3000, function () {
var host = server.address().address;
host = (host === '::' ? 'localhost' : host);
var port = server.address().port;
console.log('listening at http://%s:%s', host, port);
});
var deck = [ ];
app.get('/deck', function(req, res) {
res.send(deck);
});
app.post('/deck', function(req, res) {
console.log(req.body);
var card = req.body;
deck.push(card);
res.send(deck);
});
Given this code I could navigate to "localhost:3000/deck and any changes I made were stored in the array and displayed at this address. Simple enough. I've taken that a step farther and implemented a database, mySQL and have successfully written methods for insertion, select, delete, etc..
<script>
$("submit").on("click", function(){
$.post("/users", { name: username.value, password: psw.value, email: email.value}, function(){
console.log("post successful..");
});
});
</script>
<body>
<form>
username:<br>
<input type="text" name="username"><br>
password:<br>
<input type="password" name="psw"><br>
email:<br>
<input type="text" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
I added the above form jquery script to the html page. And attempted to add the server functions below.
app.get('/users', function (req, res) {
});
app.post('/users', function (req, res) {
console.log(req.body);
});
I thought that this would allow me to use the req.body object on submission of the form. Please correct me if I'm going about this the wrong way, I would be grateful for any help/tips.
You can do two things:
Use event.preventDefault() to stop the form submission.
Change the button type to button instead.
As you have not prevented the form to submit so, whenever you click the submit button it submits the form and it makes a default get request if method attribute to post is not been provided.
$("submit").on("click", function(ev){
ev.preventDefault(); // <-------- HERE
$.post("/users", { name: username.value, password: psw.value, email: email.value}, function(){
console.log("post successful..");
});
});
Or make a small change at your markup:
<input type="button"....../>
In the form.
As per your latest comment, add a class/id attribute to the button and change the selector:
<input type="submit" id="submit"...../>
Now in js you have to use this:
$("#submit") // <---- notice the # which denotes the ID selector in jQuery.
Related
Given the following html form:
<form class = "new-date" method = "POST" action = "http://localhost:5600/postDate">
<h3>Owner</h3>
<input type ="text" name = "ownerName" class = "form-element global" id="owner">
</select>
<h3>Pet</h3>
<input type = "text" name = "petName" class = "form-element global" id = "pet">
</select>
<h3>Schedule the date</h3>
<input type="date" id="birthday" name="birthday" class = "form-element global" id="date">
<h3>Description</h3>
<textarea class = "form-element description-text" placeholder= "What is wrong with your pet?" name ="problem" ></textarea id="problem"><br>
<input type="submit" class = "form-element btn" value="Add">
</form>
Im trying to make a post method that is located inside my server.js (Node):
const exp = require('express');
const path = require('path');
var bodyParser = require('body-parser');
const app = exp();
/*DATABASE AND QUERIES*/
const mysql = require("mysql2");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "control_clientes",
connectionLimit: 5
});
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.post('/postDate', (req, res)=>{
console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
});
After submitting and sending the client side data to my server, the html page is not properly doing the reload task:
As can see in this image, the reload thing is still going. I'm not sure why it does that.
Im new to Node JS, do you have any idea what is going on with the unfinished reload thing?
Try this
app.post('/postDate', (req, res)=>{
console.log(req.body.ownerName); //TO CHECK IF IM RECEIVING THE DATA. IT WORKS
res.json({message: 'OK.'})
});
If you want your browser to stop spinning (loading) you need to send a response from a server.
For example send a json response with req.body (echo endpoint)
app.post('postDate', (req, res) => {
console.log(req.body.ownerName);
res.json(req.body);
})
I am using the Node.JS POST method to submit a form to my server. It is transmitted to the server fine; no problems occur at this stage. However, when I use io.emit with socket.io to transfer the data back to the client, nothing seems to happen client-side. Nothing is printed to the console and I'm getting no errors there or in Command Prompt (where I'm running the server from).
index.html:
<form id="schoolCreateForm" action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
</script>
app.js:
var express = require('express');
var app = express();
var serv = require('http').Server(app);
var io = require('socket.io')(serv);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/createSchool', function(req, res) {
response = {
school_name: req.body.schoolName,
school_private: req.body.schoolPrivate,
entry_password: req.body.entryPassword
};
console.log(response);
res.sendFile(__dirname + '/client/index.html');
io.emit('updateSchool', response);
});
serv.listen(3000);
console.log("Server started on localhost://3000");
Does anyone know what's going on?
<form action="http://localhost:3000/createSchool" method="POST">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit" id="schoolCreateForm">Submit</button>
After submitting your form data it will reload your page, it means socket connection will be ended. If you want to see a response with socket make ajax.post request without reloading the page.
<form id="schoolCreateForm">
School name: <input name="schoolName" type="text"><br><br>
Private?: <input name="schoolPrivate" type="checkbox"><br><br>
Entry password: <input name="entryPassword" type="password"><br><br>
<button type="submit">Submit</button>
</form>
<script>
document.querySelector('#schoolCreateForm').addEventListener('click',
function(e) {
e.proventDefault() // this line will not all to reload page after
/// submitting the
//form data
### writh you ajax request functionality here
})
var socket = io();
socket.on('updateSchool', function(response) {
console.log(response);
document.getElementById("headerSchoolName").innerHTML = data.schoolName;
});
I am writing a node.js app to authenticate with LinkedIn and it isn't working. The problem is that I am redirecting to (what appears to be) the correct URL, but instead of being forwarded to a page that queries the user to authorize their credentials, I get a "page not found" message.
I have created a LinkedIn "App". Below are my "authorized redirect URLs":
HTML
<div id="root">
<button id="auth-button"> Login </button>
</div>
Client JS
function onSignInButtonClick() {
// Open the Auth flow in a popup.
window.open('/redirect', 'firebaseAuth', 'height=315,width=400');
};
var button = document.getElementById("auth-button");
button.addEventListener("click",function(){
onSignInButtonClick();
});
Server code
const credentials = {
client: {
id: "LINKEDIN_CLIENT_ID-1-2-3-4",
secret: "LINKEDIN_CLIENT_SECRET-1-2-3-4",
},
auth: {
tokenHost: 'https://www.linkedin.com/oauth/v2/authorization'
}
};
const oauth2 = require('simple-oauth2').create(credentials);
var express = require("express");
var app = express();
app.use(express.static("public"));
app.get('/', (req, res) => {
res.sendFile('landing.html',{
root:'public'
})
});
app.get('/redirect', (req, res) => {
const redirectUri = oauth2.authorizationCode.authorizeURL({
response_type:"code",
redirect_uri: "http://www.localhost:3000/callback",
state: "some-cryptic-stuff-98471871987981247"
});
res.redirect(redirectUri);
});
app.get('/callback',(req, res) => {
console.log("linkedin-callback route invoked");
res.send("linked in callback working")
});
app.listen(3000, function(err) {
console.log('Server works');
});
When the user clicks the button they are redirected to a URL that is identical in structure to the one that is given as a "sample call" (below) in the LinkedIn developer reference.
https://developer.linkedin.com/docs/oauth2#
However instead of seeing the prompt in the image above, my code gives them this:
The redirect_uri you have registered in LinkedIn (http://localhost:3000/callback) is different to what you are actually sending (http://www.localhost:3000/callback). This might be the issue as it causes an invalid redirect_uri error.
I am trying to write a simple web application in node.js that will allow a user to enter data into a search bar and then send the input to the server which will query the database with the user generated input. I already have my database set up and connected, but here is my code:
SERVER
var express = require('express');
var sql = require('mysql');
var app = express();
//Configure application
app.set('views',__dirname + '/views'); //Set views directory
app.use(express.static(__dirname + '/JS'));
app.set('views engine', 'ejs'); //Set view engine to ejs
app.engine('html', require('ejs').renderFile);
app.use(function(req, res, next){ //Set no cache for the server
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.header('Expires', '-1');
res.header('Pragma', 'no-cache');
next();
})
//Connect to mySQL database
var db = sql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'homeDB'
});
db.connect(function(err){
if(err){console.log('there was an error connecting to the database' + err);}
})
//Set up routers (request handlers)
//Return home page when root('/') is requsted
app.get('/', function(req, res){
res.render('index.html');
});
app.get('/search', function(req, res){ //GET method to access DB and return results in JSON
db.query('SELECT * FROM products WHERE product LIKE "%' + req.query.key + '%"',
function(err, rows, fields){
if(err) throw err;
var data = [];
for(i=0;i<rows.length;i++){
data.push(rows[i].product);
}
res.end(JSON.stringify(data));
});
});
app.get('/typeahead.bundle.js', function(req, res){ //When typeahead is requested, send it to client
var fileName = './typeahead.bundle.js';
var options = {
cacheControl: false,
root: __dirname
}
res.sendFile(fileName, options, function(err){
if(err){
console.log('there was an error sending ' + fileName + err);
res.status(err.status).end();
}else{console.log('Sent! ' + fileName);}
});
});
app.post('/search', function(req, res){ //POST method to access DB and return results in JSON
db.query('SELECT * FROM products WHERE product LIKE "%' + req.params.input + '%"',
function(err, rows, fields){
if(err) throw err;
var data = [];
for(i=0;i<rows.length;i++){
data.push(rows[i].product);
}
res.end(JSON.stringify(data));
console.log(req.params.input);
});
});
var server = app.listen(3000, function(){ //Start the server on port 3000
console.log('server has started on localhost:3000...')
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Express Application</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/typeahead.bundle.js" type="text/javascript"></script>
</head>
<body>
<h1>Thank you for connecting to my server!</h1>
<form class="search" action="typeahead" method="post">
<input class="form-control typeahead tt-query" type="text" name="input" placeholder="Search">
<input class="btn btn-primary" type="submit" name="input" value="Submit">
</form>
<script type="text/javascript">
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: 'http://localhost:3000/search?key=%QUERY',
limit: 10
});
});
</script>
</body>
</html>
Now I have all my routers and middleware setup in node, but I can't seem to figure out how to simply get the user input to send to the server. I tried using the 'req.query.key' to get the value of the search input but that actually returns as undefined in my case. So, is there anyway to actually recieve the text through the 'req.query.key' variable, also is there a more 'conventional' method of making a simple database search bar?
P.S. I am still very new to programming in Express and Node.js as a whole, so if you see any common mistakes or 'sloppy' code I'd love to hear your feedback.
You can try using npm body-parser, in place of req.params.key you can put req.body.input (where input is the name of the input element).
Put this:
app.use(bodyParser.urlencoded({
extended: true
}));
Before your template engine configuration (before setting your views)
Have you tried getting the params in the following way
var key = request.options.key || (request.options.where && request.options.where.key) || request.param('key');
So basically, I have a form and I cannot fetch data typed into it.(I'm using angular and node.js)
req.body
req.params are both empty
My html form :
<form ng-submit="sendTradelink()">
<md-input-container class="md-accent">
<label>Enter your tradelink</label>
<input ng-model="tradelink">
</md-input-container>
<md-button type="submit" class="md-raised md-accent">Send</md-button>
</form>
Controller :
$scope.sendTradelink = function () {
Auth.send()
.success(function (res) {
$location.path('/');
});
}
Service :
authFactory.send = function (tradelink) {
return $http.post($api.url + 'tradelink', {tradelink: tradelink});
};
Server side file where I want to work with data inserted into form:
api.post('/tradelink', function(req, res){
console.log(req.user.id);
console.log(req.params);
console.log(req.body);
res.json({
success: true,
message: 'tradelink received'
})
});
logs for controlling, empty every time.
As mentioned in comments, Express does not parse the body. POST requests are much more complex that GET ones, so the parser lies in a separate package, body-parser:
npm install --save body-parser
// server.js
api.use(bodyParser.urlencoded({
extended: true
}));
api.post('/tradelink', function(req, res) {
console.log(req.body.tradelink);
});
#Amadan answer is right. You also need to update the controller:
Auth.send($scope.tradelink)