when i try to run nodejs, there is an error in "throw er;" in the "css" part, but it doesn't exist. Someone can see the error?
var http = require('http'),
fs = require('fs');
http.createServer(function(req, res) {
fs.readFile('./index.html', function (err, data) {
if (err) { throw err; }
res.writeHeader(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
fs.readFile('./main.js', function (err, data) {
if (err) { throw err; }
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(data);
res.end();
});
fs.readFile('./style.css', function (err, data) {
if (err) { throw err; }
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}).listen(8000);
you have a few problems in your code:
at the main.js part you use res.end instead of res.write
you call res.end 3 times
you try to return 3 files in one request, you should check the path (req.url) and return the right file by that. or you can use express or other framework.
Related
I have an existing async function:
async doJSONGetRequest(getUrl, accessToken) {
return new Promise(function(resolve, reject) {
const reqHeaders = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`,
};
console.info('url = ' + getUrl);
request.get({
url: getUrl,
headers: reqHeaders,
}, function(err, response) {
if (err) return reject(err);
try {
// console.debug(`response = ${response.body}`);
const parsed = JSON.parse(response.body);
return resolve(parsed);
} catch (err) {
return reject(err);
}
});
});
}
}
I'm trying to test it with Jasmine(v4).
Of course, I don't want this thing to actually make an HTTP request, so I tried rigging up a spy on the 'request' package's 'get' function in the 'beforeAll' section:
describe('RAPIDAPIService', function() {
beforeAll(async function() {
spyOn(request, 'get')
.and
.callFake(async (parameters) => {
if (parameters.url === 'http://localhost/api/getSomething') {
const rsp = {};
rsp.body = 'good stuff';
return rsp;
} else if (parameters.url === 'http://localhost/api/whoops') {
return new Error('401 not found');
} else {
return null;
}
});
});
it('doJSONGetRequest should run successfully', async () => {
expect(api.doJSONGetRequest).toBeDefined();
const res = await api.doJSONGetRequest('http://localhost/api/getSomething', '12345678');
expect(data).toEqual('good stuff');
});
it('doJSONGetRequest should resolve errors properly', async () => {
expect(api.doJSONGetRequest).toBeDefined();
const res = await api.doJSONGetRequest('http://localhost/api/whoops', '12345678');
const expectedError = new Error('401 not found');
expect(res).toEqual(expectedError);
});
Console log statements seem to indicate that I'm actually getting past / returning something from my "await" calls in the "it" tests. But the spies are actually working / detecting that the url's have been called.
(Note that I'm not including here other tests in the same file that do not make asynchronous calls and ARE working... just so you know that there's no problem accessing the actual "api" library and its functions.)
These two tests keep failing with "Error: Timeout - Async function did not complete within 5000ms". And like I said, it seems like they're not returning back to the tests from their calls to the doJSONGetRequest function.
Any thoughts?
Thanks!
I am thinking the issue is the mocking. request.get seems to take two parameters and I am thinking you need to call the 2nd parameter (callback function) once you are done so the resolve can be called.
Try this:
spyOn(request, 'get')
.and
// add callbackFunction as 2nd argument
.callFake((parameters, callbackFunction) => {
if (parameters.url === 'http://localhost/api/getSomething') {
const rsp = {};
rsp.body = 'good stuff';
callbackFunction(null, rsp);
} else if (parameters.url === 'http://localhost/api/whoops') {
callbackFunction({ error: '401 not found' }, {});
} else {
callbackFunction(null, null);
}
});
I am trying to deploy my first function, but I am stuck, I don t understand what is wrong in my code.
This is the error that I receive
functions[sendNotifications(europe-west1)]: Deployment error.
Function failed on loading user code. Error message: Error: please examine your function logs
to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs
Even in that link I did not find something that could help me understand where is the problem, what I am doing wrong. I hope someone of you guys can help me, here it is my code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
const async = require('async');
admin.initializeApp(functions.config().functions);
exports.sendNotifications = functions
.region('europe-west1')
.pubsub.schedule('every day 13:00').onRun(async context => {
async.waterfall([
function(callback) {
url = 'http://niksimoni.pythonanywhere.com/api/pulizie_domani';
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
const APIResponse = JSON.parse(body);
callback(null, APIResponse.strade);
}
else {
callback('Error parsing the data');
}
})
},
function(streets, callback) {
for (var i = 0; i < streets.length; i++) {
async.waterfall([
function(callback) {
let street = streets[i];
url = 'http://niksimoni.pythonanywhere.com/api/data_pulizie?indirizzo=' + street;
request(url, (error, response, body) => {
if (!error && response.statusCode === 200) {
const APIResponse = JSON.parse(body);
var topic = street;
var message = {
data: {
title: street,
subtitle: 'Pulizia domani alle ' + APIResponse.ora,
},
topic: topic
};
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
callback(null, message);
} else {
callback('Error parsing the data');
}
})
}
], function(error, results) {
if (error) {
console.log(error.message);
}
});
}
callback(null);
}
], function(error, results) {
if (error) {
console.log(error.message);
}
});
});
Solved, I had to add the dependencies to the packages.json file
We are trying to connect our evothings app up to a meteor server.
To do this we are using a lib called asteroid. However we are unable to connect and run methods. We are absolutly sure this is not a server issue since we have some separate client code for testing that works flawlessly with it.
Evothings says it should work with websockets, and we aren't getting any error output, but all our method calls are returning nothing.
Here is the code:
var _asteroid = require('asteroid');
var Asteroid = (0, _asteroid.createClass)('password-login');
var asteroid = new Asteroid({ endpoint: 'wss://[url]/websocket' });
var currentLogin = null;
$('#login').submit(function(event) {
event.preventDefault();
login($('#login_username').val(), $('#login_password').val());
});
$('#create').submit(function(event) {
event.preventDefault();
newUser($('#create_username').val(), $('#create_password').val(), $('#create_id').val());
});
$('#occupy').click(function(event) {
setStatus(0);
});
$('#vacant').click(function(event) {
setStatus(1);
});
$('#refreash').click(function() {
getEmptyRooms();
});
window.newUser = function (username, password, roomId) {
$('#create_error').text('');
asteroid.call("accounts.newUser", username, password, roomId).then(function (result) {
console.log("Success");
login(username, password);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#create_error').text(error.message);
});
}
window.login = function (username, password) {
$('#login_error').text('');
asteroid.loginWithPassword({ username: username, password: password }).then(function (result) {
console.log(result);
currentLogin = result;
$('#current').html('Current User: ' + username);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#login_error').text(error.message);
});;
}
window.getEmptyRooms = function () {
asteroid.call("rooms.getAvailable").then(function (result) {
console.log(result);
$('#room_list').empty();
for(i = 0; i < result.length; i++) {
$('#room_list').append('<li>' + result[i] + '</li>');
}
}).catch(function (error) {
console.log("Error");
console.error(error);
});
}
window.setStatus = function (status) {
$('#status_error').text('');
if (currentLogin != null) {
asteroid.call("rooms.setStatus", status).then(function (result) {
console.log(result);
}).catch(function (error) {
console.log("Error");
console.error(error);
$('#status_error').text(error.message);
});
} else {
console.log('please login first');
$('#status_error').text('please login first');
}
}
As far as I know, the require() function works only in node.js, not in browser environment such as Evothings Viewer or Cordova, so you'll need some alternative means of loading the "asteroid" lib. Browserify?
How did you look for error output? The Evothings Tools window? If so, did you add this snippet to your index.html file?
<script>
// Redirect console.log to Evothings Workbench.
if (window.hyper && window.hyper.log) { console.log = hyper.log }
</script>
Perhaps this error isn't exclusive to the Evothings environment. Have you tested the app in a regular web browser?
Are you using proper certs?
Self signed will not work. The Evothings app is served via wss and since it runs "headless" so to speak (not a normal browser) it can't ask the user about allowing a self signed cert, so it will fail. Note that AFAIK ANY issue with the cert will make it fail.
I would like to know why this code using async and await does not work.
// I promisified `github.users.get` which is asynchronous
function getUserData() {
return new Promise(function (resolve, reject) {
github.users.get({}, function (err, res) {
if (err) {
reject(err);
} else {
resolve(res)
}
});
});
}
// Similar to above
function getUserEmails() {
return new Promise(function (resolve, reject) {
github.users.getEmails({}, function (err, res) {
if (err) {
reject(err);
} else {
resolve(res)
}
});
});
}
(async function () {
let github = new GithubAPI({version: '3.0.0'});
github.authenticate({
type: 'oauth',
token: // auth token
});
let userData = await getUserData(); // stuck
let emails = await getUserEmails();
// do something
}());
The code never continues beyond let userData = await getUserData();. It is stuck there.
What am I doing wrong? I am using Meteor 1.3.1.
I want to implement error handling in my app but when I throw a Meteor.Error my server crashes. This might be because I'm using a future to wait for the result. How can I get this running?
Meteor.methods({
'/app/pdf/download': function (url, name) {
check(url, String);
check(name, Match.Any);
if ( ! name) {
name = url.split('/').pop();
} else {
name += '.pdf';
}
var Future = Meteor.npmRequire('fibers/future');
var Download = Meteor.npmRequire('download');
var future = new Future();
var download = new Download({ extract: true, strip: 1 })
.get(url)
.dest(process.env.PWD + '/staticFiles')
.rename(name);
// Run download
download.run(function (err, files, stream) {
if (err) {
throw new Meteor.Error(500, 'Couldn\'t download file');
}
future.return(name);
});
return future.wait();
}
});
Yes, it is because you are throwing it in another call stack.
You could try:
var error;
download.run(function (err, files, stream) {
if (err) {
error = err;
}
future.return(name);
});
var result = future.wait();
if (error)
throw new Meteor.Error(500, 'Couldn\'t download file');
return result;
Either way I recommend using Meteor.wrapAsync for your purpose.
var sync = Meteor.wrapAsync(function (done) {
download.run(function (err, files, stream) {
if (err) {
done(new Meteor.Error(500, 'Couldn\'t download file'));
}
else {
done(err, name);
}
});
};
return sync();
If you are using Meteor < 1.0, its Meteor._wrapAsync().