JSON.parse unexpected token s at position 0 - javascript

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.

Related

Node.js: receiving input from HTML select without document.getElementById

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}`);
});

jQuery get method not working properly with two parameters passed to request

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

Simple Node.js chat program NOT using socket.io

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.

Ajax with node.js

i know some persons asked this question before but i don't understand answers :/
I'm using node.js, and i realy want to use Ajax in it.
My code is :
var $ = require('jquery');
var http = require("http");
var ws = require("nodejs-websocket");
var fs = require("fs");
var colors = require('colors');
http.createServer(function (req, res) {
fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauDeJoueur = new Array();
var server = ws.createServer(function (connection){
connection.nickname = null
connection.on("text", function (str){
if (connection.nickname === null){
connection.nickname = str;
console.log((connection.nickname+" arrive sur PixelWorld !").green);
}
else{
var code = str.substring(0,2);
var reste = str.substring(2,str.length);
switch(code){
case "01":
var coupe = reste.split("4H[m~Ft7");
var mail = coupe[0];
var mdp = coupe[1];
$.ajax({
url: "fonctionPHP/connection.php",
type: "POST",
data: {'mail': mail,'mdp': mdp},
async:false,
success: function(html){
if(html == "OK"){
console.log("oui");
}
else{
console.log("non");
}
}
});
break;
case "02":
break;
}
}
})
connection.on("close", function (){
console.log((connection.nickname+" a quitté PixelWorld !").red);
})
})
server.listen(8081)
function broadcast(str) {
server.connections.forEach(function (connection) {
connection.sendText(str)
})
}
My problem is at the line "$.ajax({".
The server notice me when a user is coming, it's ok. But when he send a message with a 01 code, node crash and say me :
$.ajax({
^
TypeError: Object function ( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
} has no method 'ajax'
at Connection.<anonymous> (/var/www/dhkuhnuhbnkiuh/app.js:46:8)
at Connection.EventEmitter.emit (events.js:95:17)
at Connection.processFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:516:9)
at Connection.extractFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:458:14)
at Connection.doRead (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:209:23)
at Socket.<anonymous> (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:52:8)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
Sorry if my English isn't good, I'm French and bad at English. :/
Thank you for your help :D
Doing a request from nodejs is fairly easy, dont have to use $.ajax at all. You can use the npm request module. $.ajax is built for firing requests from the browser. But if you 'really' want to use $.ajax on node, I think you can read through this question
First,we begin with understanding AJAX and Node.Ajax is a client-side xml-based technology that automatically updates contents of a web page, without the page having to reload. Node.js is a server-side scripting language.
To illustrate this clearly, we will create a client client.html file and a server server.js
Aside from having npm installed, we will install express middleware and some of it's dependencies that we are going to use.
npm install --save express body-parser body-parser-xml
Let's begin by writing our server.js file. This file is going to parse xml requests sent AJAX. After processing request body, server should then send response back to client.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
require('body-parser-xml')(bodyParser);
app.use(bodyParser.xml({
limit: '1MB',
XmlParseOptions: {
normalize: true,
normalizeTags: true,
explicitArray: false
}
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/" + "client.html");
});
app.post('/library', bodyParser.urlencoded({ extended: false }), function(req, res) {
console.log(req.body);
var title = req.body.book.title;
var author = req.body.book.author;
var year = req.body.book.year;
console.log(title + " " + author + " " + year);
//optional operations like database can be performed here
// we are sending a response mimicking a successfull search query
res.end("Book Found in library");
});
var server = app.listen(8080, function() {
var host = '127.0.0.1';
var port = server.address().port;
console.log("Server running at http://%s:%s\n", host, port);
});
Next, create client.html file. This file will have simple form that when submitted call on an AJAX function that in turn sends xml data to server.js then waits and process response
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function Search() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.getAllResponseHeaders();
xmlhttp.open('POST', 'http://127.0.0.1:8080/library', true);
console.log(document.getElementById('title').value);
console.log(document.getElementById('author').value);
var text = "<book>" +
"<title>" + document.getElementById('title').value + "</title>" +
"<author>" + document.getElementById('author').value + "</author>" +
"<year>" + document.getElementById('year').value + "</year>" +
"</book>";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert(xmlhttp.responseText);
console.log("All ok. You hit the server");
}
}
};
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(text);
}
</script>
</head>
<body>
<form name="" method="POST" action="">
Title:<input type="text" name="title" id="title">
Author:<input type="text" name="author" id="author">
Year:<input type="text" name="year" id="year"><br>
<br>
<input type="button" value="Search" onclick="Search()" />
</form>
</body>
</html>
Hope this guide helps in future. Thanks

Node.js & Express file upload issue

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?

Categories

Resources