I'm working on a node.js project that involves selecting someones' name and redirecting the user for more information. However, when I try to console.log the result, just to check that I can retrieve the values, I get nothing.
Below is an example of my code:
function displayDetailed(data, req) {
names = data[0];
var input = '<select name = "dropDown" onChange = "testing(this)">;
for (var i = 0; i < names.length; i++) {
input += '<option value= "' + i + '" name = "employee" > ' + names[i] + ' </option>';
}
input += '</select><br>';
var myData = {
test: req.body
}
console.log(myData);
return '<!DOCTYPE html><head></head><body>' + input + '</body></html>';
}
function testing(name) {
console.log('Testing! ' + name);
}
Clearly, I just want the employee's name to be printed off onto the console for the moment. However, nothing is popping up on the console, be it the name or any errors.
I've also tried multiple solutions I've seen on other StackOverflow posts ( Example, Example1 ). That's where I got the idea for the test var. For some reason, the request's body does not exist when I try to call it and just returns undefined.
I also can't call document.getElementById since node.js doesn't have a DOM. The solutions linked implement this function, which I cannot call because node.js doesn't allow me to call the html document that the user is working on.
This function will be returning an HTML string to a res.send call within an express app.get.
Short answer:
I suspect your problem is you're not using a body parser middleware to parse the request body.
Longer version:
Suppose you have an HTML file named index.html in a directory named html in the root of your project:
<!doctype html>
<meta charset=utf-8>
<title>Test</title>
<body>
<form action="/" method="post">
<select name="values">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit">
</form>
</body>
You can use the built-in static middleware to serve that file to clients (or build the HTML string and send it as a response to clients or maybe use a template engine and make your life easier) and then use a body parser middleware (like this one) to parse the request body when the form is submitted:
const http = require('http');
const path = require('path');
const bodyparser = require('body-parser'); // npm i body-parser
const express = require('express');
const app = express();
const PORT = process.env.PORT || 8080;
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
app.use(express.static(path.join(__dirname, './html')));
app.use(bodyparser.urlencoded({extended: true}));
app.post('/', (req, res) => {
res.setHeader('content-type', 'text/plain');
res.end(`You have selected: ${req.body.values}`);
});
Related
I'm trying to learn about JSON and watching a Udemy video. During the code along I get the JSON.parse unexpected token s at position 0. I'm not quite sure how to fix the error or what it entails entirely.
I've checked out the Q&A section of the video and it seems like a lot of people are running into the same error but no solution is working. I've also checked out some of the stackoverflow answers, but I'm so new to the concept of JSON that it makes zero sense. Any help would be greatly appreciated!
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request"); // use to do a request to an external
server
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
var crypto = req.body.crypto;
var fiat = req.body.fiat;
var URL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/";
var finalURL = URL + crypto + fiat;
request(finalURL, function(error, response, body) {
var data = JSON.parse(body)
var price = data.last;
var currentDate = data.display_timestamp;
res.write("The current date is " + currentDate);
res.write("<h1>The current price of" + crypto + " is: " + price + fiat +
"</h1>");
res.send();
});
});
app.listen(3000, function() {
console.log("Server started on port 3000.");
});
HTML Part
<form action="/" method="post">
<select name=" crypto">
<option value="BTC">Bitcoin</option>
<option value="ETH">Ethereum</option>
<option value="LTC">Lightcoin</option>
</select>
<select name="fiat">
<option value="USD">US Dollars</option>
<option value="GBP">GB Pounds</option>
<option value="EUR">EU Euros</option>
</select>
<button type="submit" name="button">Check</button>
</form>
The expected output should be when you select the crypto currency and curreny (like $, pounds , euros) it will tell you what the price of the crypto currency is.
When making a request with the wrong URL to this API, you get a string back which results into JSON.parse returning this error. it could be that the API provider changed this link overtime. Try visiting this api route in your browser and see if it works.
Most likely you're passing the wrong URL.
I am trying to send firstname and lastname to an api request using jQuery get method. It works fine with only one parameter ie with only first name but does when I add lastname to the request.
It works fine if url ="http://localhost:5000/name?firstname="+h1;
but does not work if url = "http://localhost:5000/name?firstname="+h1+"&lastname="+h2; In later case, the desired output is displayed for a sec and then disappears and url changes to "http://localhost:5000/?", the function is called from "http://localhost:5000/"
Here is my javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#submitButton").click(function(e){
var h1 = $("#handle1").val();
var h2 = $("#handle2").val();
var u = "http://localhost:5000/name?firstname="+h1+"&lastname="+h2;
//works fine if u = var u = "http://localhost:5000/name?firstname="+h1; though lastname is displayed undefined in the output
alert(u);
$.get(u, function(data){
$('.result').html(data);
})
});
});
</script>
and here is my Express API code:
var express = require('express');
var app = express();
var path = require("path");
const PORT = process.env.PORT || 5000
app.listen(PORT, function(){
console.log('server running on port ' + PORT);
})
app.get('/name', function(req, res){
res.send("Full Name: "+ req.query.firstname + " " + req.query.lastname);
});
Your Ajax $.get request should look like the code snippet below. If the served HTML is also running via http://localhost:5000/ then you can completely omit the relative URL.
$.get('name', {'firstname': h1, 'lastname': h2}).done(function(data) {
$('.result').html(data);
});
The name in $.get corresponds to the route /name
Please think about: I'm a beginner and try to learn progamming with javascript.
My goal: I have two buttons on a website. Each of both has to start his own function on the server.
Thanks to various tutorials I manage to trigger an action on the server. But now I have to distinguish two buttons for different server actions.
server.js
var express = require('express');
var app = express();
app.set('view engine', 'jade');
app.use(express.bodyParser());
var tweetText = 'A lot of tweet text...';
var user = 'Lutz';
var account = '#name';
var relevance = 0;
var tweetID_str = 0;
var RTs = 0;
//Send data from client/browser to server
app.post('/', function (req, res) {
console.log('works');
console.log(req.body);
});
//Send data from server to client
app.get('/', function(req, res){
relevance = relevance + 1;
tweetID_str = tweetID_str + 2;
RTs = RTs +3;
console.log('relevance: '+relevance+' userbytwo: '+tweetID_str);
res.render('index', { tweetText: 'Text: '+tweetText, account: '#User: '+account, user: 'User: '+user, relevance: 'RT per follower: '+relevance, tweetID_str: 'ID_str: '+tweetID_str, RTs: 'RTs: '+RTs });
/* updated this line */
});
app.listen(3000);
index.jade
doctype html
html(lang="de")
head
body
div
div!= tweetText
div!= account
div
div!= user
div!= relevance
div!= tweetID_str
div!= RTs
form(method='post')
div
input(type='submit', id='good', value='good')
input(type='submit', id='bad', value='bad')
<!-- input(type='text', name='username') -->
I guess, I have to parse the website action. Depending on the result the server starts his action. I'm right or wrong? And what do I have to do, that my code works?
You could probably capture the id of the button after click and then call the necessary action based on the id received using jquery. For example you could do something like:
$('#good').click(function(){
// Do the action on server that you want to do on click of good button.
});
$('#bad').click(function(){
// Do the action on server that you want to do on click of bad button.
});
Not sure if this is what you wanted ? Let me know your exact needs for more help.
You can use JQuery AJAX call to invoke a method as below.
$(document).ready(function() {
$('#good').click(function(){
$.ajax({
url: "/home"
}).then(function(data) {
alert(data); // Do whatever you want to do with response.
});
});
});
I am trying to learn Node and build a simple chat application. It seems like everyone uses socket.io. I would like to understand how to do this on a more fundamental level using get and post.
Basically, all I want to do is have a form that takes an input and reposts it below the form for everyone to see.
This is what I have so far:
//Requirements
var express = require('express');
var app = express();
//GET
app.get('/', function (req, res) {
// res.send('Hello World!');
var response =
"<HEAD>"+
"<title>Chat</title>\n"+
"</HEAD>\n"+
"<BODY>\n"+
"<FORM action=\"/\" method=\"get\">\n" +
"<P>\n" +
"Enter a phrase: <INPUT type=\"text\" name=\"phrase\"><BR>\n" +
"<INPUT type=\"submit\" value=\"Send\">\n" +
"</P>\n" +
"</FORM>\n" +
"<P>phrase</P>\n"+
"</BODY>";
var phrase = req.query.phrase;
if(!phrase){
res.send(response);
}else{
res.send(response);
res.send(phrase);
}
});
//For testing
app.get('/test', function(req, res){
res.send('I am a robot');
console.log('told visiter I am a robot');
});
//Run the app
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I've been trying a bunch of things, but I am pretty stumped.
Did you hear about messaging backend jxm.io?
It works with JXcore (open sourced fork of Node.JS). JXM itself is an open source project, which you can find on github: jxm.
It's really fast and efficient, you can check some tutorials. For example, below is minimal code, that you need to run on server-side:
var server = require('jxm');
server.setApplication("Hello World", "/helloworld", "STANDARD-KEY-CHANGE-THIS");
server.addJSMethod("serverMethod", function (env, params) {
server.sendCallBack(env, params + " World!");
});
server.start();
The client's part can be found here:
Browser Client (JavaScript)
JXM also supports Java clients (runs on android) and node clients.
Going nuts trying to get past this. Should be trivial, but I'm obviously doing something stupid. Goal is to upload a file inside Express. In short request.files is coming back as undefined in my route handler :
//modules ==========================================
// ExpressJS 4.0 used for the middleware and web framework
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var flash = require('connect-flash');
var jsxml = require("node-jsxml");
var XMLWriter = require('xml-writer');
var request = require("request");
var fs = require('fs');
var app = express();
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
// Did I screw this up??!
app.use(bodyParser({keepExtensions:true,uploadDir: __dirname + '/public/uploads'}));
app.engine('html', require('ejs').renderFile);
app.use(cookieParser('Ronaldinho'));
app.use(session());
app.use(flash());
My file system:
Here's the form where a file is submitted (via a plugin called DropZone):
<div id="dropzone">
<form action="/uploads" name="upload" class="dropzone" id="demo-upload" enctype="multipart/form-data" method="post">
<input type="file" name="theFile" />
</form>
</div>
and the handler for the route:
app.post('/uploads', function (request, response) {
console.log('arrived');
console.log('1st TEST: ' + (request.files));
console.log('2nd TEST: ' + request.files.theFile.name);
fs.readFile(request.files.theFile.path, function (err, data) {
var newPath = "/home/path/to/your/directory/"+request.files.theFile.name;
console.log (newPath);
fs.writeFile(newPath, data, function (err) {
res.send("hi");
});
});
});
I hit the function above every time I upload a file, but find that request.files is undefined. Here's the result on the console (I'm using Brackets - interesting to me that I never even see the second test hit the console window...):
Any ideas what I'm screwing up?