Express res.send not working - express

I have defined a variable so that I can store my endpoint in my express server.js file and I send it over a route called '/config' as shown below:
var webService,appConfig;
webService = "some endpoint";
appConfig = {
webServiceUrl: webService
};
app.get('/config', function(req, res) {
res.send(appConfig);
});
However, when I set up my http request like so:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
var
isReady = (xhr.readyState === 4),
isSuccess = (xhr.status === 200),
config;
if (isReady && isSuccess) {
config = JSON.parse(xhr.responseText);
window._configUrl = config;
}
}
xhr.open('GET', '/config', true);
xhr.send();
...it seems that the request is sending the index file instead of the variable I have defined. I have no idea why this would be happening. Any thoughts?

Related

trying to call api through xhr in Vuejs ,using promise to store response ,doesnt recognize .then()

I am trying to call api through xhr ,since axios is not working,how do i store response in a variable ,if i use promise .then() it throws error ,Below is what i am trying to do
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com', true).then(response=>{
console.log(response);
})
xhr.send();
error ,cannot read then
i got the answer.it works!!
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};

Is there a way to fix Cannot read property 'post' of undefined?

I'm running a page in vue with a form, it submits and returns data to and from an API, I'm getting a 'post' of undefined error in the console and I can't seem to figure out what's going on.
<script>
methods: {
StartClient: function () { // Initiate XMLHttpRequest as aHttpRequest for GET
this.get = function(Url, Callback){
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow GET
aHttpRequest.open("GET", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(null);
}
this.post = function(Url, message, Callback) { // initiate XMLHttpRequest as aHttpRequest for POST
var aHttpRequest = new XMLHttpRequest();
aHttpRequest.onreadystatechange = function() {
if (aHttpRequest.readyState == 4 && aHttpRequest.status == 200)
Callback(aHttpRequest.responseText);
}
// use aHttpRequest with response headers, to allow POST
aHttpRequest.open("POST", Url, true);
aHttpRequest.setRequestHeader("X-Api-Key", "eVnbxBPfn01kuoJIdfgi46TiYNv8AIip1r3WbjsX");
aHttpRequest.send(message);
}
},
submitData: function () { // Start a traceroute, followed by the 'Begin' button
document.getElementById('inputBox').disabled = true;
var targetInputButton = document.getElementById("inputBox").value;
var message = '{"targetInputButton":"' + targetInputButton + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/start-trace', message, function(response) {
document.getElementById('jobId').innerHTML = response;
});
},
sendBackData: function () { // Receive traceroute data, followed by the 'Generate data' button
var jobId = document.getElementById("jobId").innerHTML;
var message = '{"jobId":"' + jobId + '"}';
this.StartClient().post('https://le75bkfcmg.execute-api.eu-west-2.amazonaws.com/dev/check-trace', message, function(response) {
document.getElementById('report').innerHTML = response;
});
}
}
}
</script>

Express js render error this.engine is not a function

I'm trying to develop a small API using express. Just want to have 2 views, which, in my case, means 2 html files. One accesing as default with "/" and the other with "/lessons", so we got 2 get controls plus another one which handles every other get input.
*Both files are in the "views" folder and their extension is: *.html
I have no problem accessing the "app.get("/lessons", function..." in fact I know I can acces to that because a simple "console.log(..)" command. The problem is that I got the next error when trying to render:
[TypeError: this.engine is not a function].
Could you help me? I can't understand where is the problem or what I'm doing wrong. I believe it's in the rendering function and has something to do with its configuration and the lessons.html file because index.html has no problem using the same approach.
var express = require('express');
var app = express();
var mod = require('./module');
app.use(express.static('public'));
app.use(express.static('views'));
var port = process.env.PORT || 8080;
app.listen(port, function() {
console.log('Node.js listening on port ' + port);
});
app.get("/", function(req, res) {
console.log("Passed through /");
res.render('index.html');
});
app.get("/lessons", function(req, res) {
console.log("passed through lessons");
res.render('lessons.html', function(err, html) {
if(err) {
console.log(err);
}
res.send(html);
});
//I have tried to to use just: res.render('lessons.html');
});
app.get("*", function(req, res) {
var usageReq = false;
var urlPassed = req.url;
urlPassed = urlPassed.substring(1, urlPassed.length); //remove first "/"
var expected = mod.seeIfExpected(urlPassed); //returns url(if url) or num(if number) or na(if it doesn't match any)
mod.processInfo(expected, urlPassed, function(answer) {
if (answer.found == false && answer.jsonRes == true && answer.info != "inserted") {
res.json({
"error": answer.info
});
} else {
if (answer.jsonRes == true) {
res.json({
"long_url": answer.url,
"short_url": answer.id
});
} else { // go to url
var newUrl = "https://" + answer.url;
res.redirect(newUrl);
}
}
});
});

Loading local JSON file with Safari Extension

Trying to load JSON file with Safari Extension.
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI +'js/data.json', true);
It gives an error "Cross origin requests are only supported for HTTP."
For example it is possible with Chrome Extenison
var xhr = new XMLHttpRequest();
xhr.open("GET", chrome.extension.getURL('/js/data.json'), true);
There you need to specify it in manifest
"web_accessible_resources": ["/js/data.json"]
Is there a similar way in Safari?
EDIT
Found a solution
It is possible through Global page
global.html
function handleMessage(event) {
if (event.name === "requestParagraphs") {
var xhr = new XMLHttpRequest();
xhr.open("GET", safari.extension.baseURI + 'js/data.json', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var articlesJSON = JSON.parse(xhr.responseText);
event.target.page.dispatchMessage('paragraphs', articlesJSON);
}
};
xhr.send();
}
}
safari.application.addEventListener("message", handleMessage, false);
injected.js
function handleMessage(msgEvent) {
var messageName = msgEvent.name;
var messageData = msgEvent.message;
if (messageName === "paragraphs") {
// ...
}
}
safari.self.addEventListener("message", handleMessage, false); // Listen response
safari.self.tab.dispatchMessage('requestParagraphs'); // Call global page

How to write into an Expressjs session with Primus

Using ExpressJs 4 and Primus, I can share the Express session.
primus.on('connection', function (spark) {
var req = spark.request; // Here, I have the Express session
req.session.foo = 'bar'; // I try to write into the session.
});
When I write the { foo: 'bar' } value into the session, I can't retrieve it from a standard http express call.
app.get('/api/...', function (req, res) {
console.log(req.session.foo); // Print undefined :'(
res.send();
});
The output is undefined. Could you explain me why?
Thanks.
According to the express-session documentation, we can save the session to the store.
https://github.com/expressjs/session#sessionsave
primus.on('connection', function (spark) {
var req = spark.request; // Here, I have the Express session
req.session.foo = 'bar'; // I try to write into the session.
req.session.save(); // Save the session to the store
});
Then, it works well!
Here's how I have it working currently (Express 4.13.4; Primus 4.0.5)
App.js
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var sockjs = require('sockjs');
var http = require('http');
var Primus = require('primus');
var realtime_functions = require('./custom_modules/realtime_functions.js');
var app = express();
var app_secret_key = 'app secret';
var cookieparser = cookieParser(app_secret_key);
var sessionstore = new session.MemoryStore();
app.use(cookieparser);
app.use(session({
secret: app_secret_key,
saveUninitialized: false,
resave: false,
store: sessionstore
}));
realtime_functions(app, cookieparser, sessionstore);
realtime_functions.js
var primus_start = function(express, cookies, store) {
var server = http.createServer(express);
var primus = new Primus(server, {transformer: 'SockJS', parser: 'JSON'})
primus.use('rooms', primusRooms)
server.listen(3000, '0.0.0.0');
primus.before('cookies', cookies);
primus.before('session', function session(req, res, next) {
try {
var sid = req.signedCookies['connect.sid'];
if (!sid) { return next(); }
req.pause();
store.get(sid, function (err, session) {
if (err) {
primus.emit('log', 'error', err);
return next();
}
if(session) {
req.sessionID = sid;
req.sessionStore = store;
req.thesession = store.createSession(req, session);
}
req.resume();
next();
});
} catch(error) {
console.log(error);
}
});
primus.on('connection', function(spark) {
spark.on('data', function(data) {
spark.request.thesession.addthis = "save this to session";
spark.request.thesession.save();
});
});
}
module.exports = primus_start;