I have a json string (coming from my Rails app):
http://localhost:3000/employees/1.json
How do I get my Node.js app to consume this data?
This is the code I have in my Node.js app right now:
var employees = JSON.parse("http://localhost:3000/employees.json")
This is the error I'm getting:
prompt$ node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
SyntaxError: Unexpected token h
- at Object.parse (native)
- at Object. (/Documents/Coding/dustin/employees.js:19:22)
- at Module._compile (module.js:441:26)
- at Object..js (module.js:459:10)
- at Module.load (module.js:348:31)
- at Function._load (module.js:308:12)
- at Module.require (module.js:354:17)
- at require (module.js:370:17)
- at Object. (/Documents/Coding/dustin/app.js:34:17)
- at Module._compile (module.js:441:26)
See this question:
Using Node.JS, how do I read a JSON object into (server) memory?
You should read the file first and then parse it.
var employees = JSON.parse(fs.readFileSync('employees.json', 'utf8'));
If for some reason your Rails app runs on some other machine, you need to make a http request for that. You could try this:
var site = http.createClient(port, host);
var request = site.request("GET", pathname, {'host' : host});
request.end();
request.on('response', function(response) {
var json = '';
response.on('data', function(chunk) {
json += chunk;
});
response.on('end', function () {
employees = JSON.parse(json);
});
});
Related
I'm receiving the error JSON Parse error: Unrecognized token '<'. but only on IOS. in android it is working fine and the JSON seams to be right. (You can put the link in your web browser and se). The error is in this line Data = JSON.parse(this.responseText); but i can't understand why. and why does is work on android and not in IOS?
var client = Ti.Network.createHTTPClient({
onload : function(e) {
Data = JSON.parse(this.responseText);
Size = Object.keys(Data).length;
AddList();
},
onerror : function(e) {
},
timeout : 15000
});
client.open("GET", http://lamadeus.virtualweb.pt/site/app_mobile/teste.php?act=getprodsdestaque);
client.send();
Have you tried printing the responseText on iOS? Usually this error indicates that the request is receiving a HTML instead of JSON.
Check after replacing :
< with <
> with >
& with & in your this.responseText and after that try to parse.
I write application for iOS, which uses Socket.IO. Sometimes my server JS-script falls with this error:
events.js:85
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at exports._errnoException (util.js:746:11)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:983:19)
What I know is:
Script workes fine when I use only application for Android. That app uses Socket.IO for Android
Script workes fine when I use only web-client (yeap, with socket.IO)
Script startes to fall when I use iOS app.
Crash happens not always and not right away. Script falls after 5-10 minutes after connection and may crash, but may not.
So, I think the problem is in server library for socket.io, but exception fires only when iOS-client connecting.
How can I handle this exception?
UPDATE
There is problem was in the OAuth module on my node.js-server, which tried to check app token but had timeout to vk.com
I've edited vkapi module in my node.js server by adding "on" event for "https.get" function:
Was:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
});
Now:
https.get(options, function(res) {
var apiResponse = new String();
res.setEncoding('utf8');
res.on('data', function(chunk) {
apiResponse += chunk;
});
res.on('end', function() {
var o = JSON.parse(apiResponse);
if (o.error) { self.emit('appServerTokenNotReady', o);
} else {
self.token = o.access_token;
self.emit('appServerTokenReady');
}
});
}).on('error', function(e) {
console.log('HTTPS error');
});
In general, you can handle these kinds of async errors by listening for the error event on whatever (e.g. request, connection, etc.) object.
The error event is special in that if there are currently no event handlers for it when it is emitted, the error will be thrown instead.
I'm getting a connection related error when defining a static query that filters an embedded document field.
I've tried to separate the embedded document in a separate schema file but didn't resolve the issue. Any ideas?
Error follows:
C:\development_GIT\myproject\app\models\mymodel.js:40
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\development_GIT\myproject\node_
modules\mongoose\lib\connection.js:205:15)
at Mongoose.connect (C:\development_GIT\myproject\node_modules\mongoose
\lib\index.js:156:15)
at Object.<anonymous> (C:\development_GIT\myproject\server.js:13:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:1
The error is launched when using the filter { text.lang_code: langCode }
option in the following model. If I don't use the embedded document and try to filter for exampe { _id: langCode } it does not throw errors.
//MyModel.js located at ./app/models
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MyModelSchema = new Schema({
name: { type: String, trim: true },
text: [{ name: String, lang_code: String }]
});
MyModelSchema .static({
findByLangCode : function(langCode, callback) {
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
}
});
mongoose.model('MyModel', CategorySchema);
The first lines of my main file server.js are:
//server.js
var express = require('express');
var env = process.env.NODE_ENV || 'development';
var config = require('./config/config')[env];
var mongoose = require('mongoose');
var fs = require('fs');
require('express-namespace');
mongoose.connect(config.db);
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file)
});
Solution was building the query in a different way. It seems that subdocuments can not be used inside find().
Before: (not working)
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
After (working)
this.find().where('text.lang_code').equals(langCode).sort('text.name').exec(callback);
Im using this all the time and it works fine for me.
this.find({ 'text.lang_code': langCode }).sort('text.name').exec(callback);
MongoDb can only handle one lvl of objects, but if you give it a string like you are doing in the .where function, mongodb will do magic and match it to subdocuments :)
Does any one Has every configure nack for the Rails Projects I happen to tried the dummy code
var http = require('http');
var nack = require('nack');
var app = nack.createProcess("/home/viren/myapp/config.ru");
http.createServer(function (req, res) { app.proxy(req, res); }).listen(8124, "127.0.0.1");
but it reported me with the following error
events.js:94
throw new Error('addListener only takes instances of Function');
^ Error: addListener only takes instances of Function
at BufferedRequest. (events.js:94:11)
at Process. (/home/viren/node_modules/nack/lib/process.js:257:21)
at Process.proxy (/home/viren/node_modules/nack/lib/process.js:3:63)
at Server. (/home/viren/simple.proxy.js:7:7)
at Server.emit (events.js:67:17)
at HTTPParser.onIncoming (http.js:1124:12)
at HTTPParser.onHeadersComplete (http.js:108:31)
at Socket.ondata (http.js:1019:22)
at Socket._onReadable (net.js:683:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)
here is my custom rack-file
require "config/environment"
use Rails::Rack::LogTailer
use ActionDispatch::Static
run ActionController::Dispatcher.new
According the source at node_modules/nack/lib/process.js:257 nack is expecting app.proxy to have a signature of app.proxy(req, res, next) with is a common idiom with connect apps. In connect, calling next("some value") is a convention as most apps have a catch all error handler at the bottom of the middleware chain. Since your not using connect, just create your own error handler.
I also created a pull request, so hopefully using next will be optional in the future. https://github.com/josh/nack/pull/25
var http = require('http'); var nack = require('nack');
var app = nack.createProcess("/home/viren/myapp/config.ru");
http.createServer(function (req, res) { app.proxy(req, res, logNackError); }).listen(8124, "127.0.0.1");
function logNackError(err) {
console.log('nack error:', err);
}
We are building a server with net module, and having hard time extracting the URL (and resource path) from the request. The following code crashes, saying:
Parameter 'url' must be a string not undefined.
File netServer.js:
var net = require('net');
var url = require('url');
var server = net.createServer(function(socket) { //'connection' listener
socket.on('connect', function(request) {
});
socket.on('data', function(request) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
});
socket.on('end', function() {
});
});
server.listen(8080, function() { //'listening' listener
console.log('server bound');
});
Any suggestions?
Are you trying to build an HTTP server? net is a TCP package, so all you get is the remoteAddress and remotePort, the rest will be sent on the data handler (which is just passed a Buffer, or a string, depending on the encoding).
Use the HTTP module for this, because it does all of the parsing for you.