So I am using this.router to change pages in my client application (the application is communicating with a server I build handling authentication). Unfortunately I am met with a CORS error in my application when I do router.push inside the .then clause. However when I use router.push outside the .then clause I receive no errors. Any idea what is causing this?
signup: function () {
this.$http.post('http://localhost:3000/signup?username='+this.username+'&password='+this.password+'&password2='+this.password2)
.then(response => {
if(response.body== "success"){
this.pass_or_fail=response.body;
// this.$router.push({name:'landing-page'}); this Gives me a CORS error
}
})
// this.$router.push({name:'landing-page'}); this works fine
}
This might not actually be a CORS issue. this inside the .then callback is bound to the callback, and not to the Vue instance.
To test this idea, on the first line of the signup function, do this...
signup: function () {
const vm = this
...
and then inside the callback use vm instead of this...
.then(response => {
...
vm.$router.push(...)
If that works, then make sure to also do vm.pass_or_fail=response.body
Related
The /api/user/ request to make $auth.loggedIn available happens after client already loads/started loading. This makes some of my modules render and then disappear after $auth.loggedIn has turned true/false, making everything look messy on page load.
It would be ideal if the call to /api/user/ happened in the same way an asyncData request works so that $auth.loggedIn is available before anything renders. Is there any setup/config that makes this possible ? I'm using the universal mode.
You can use the middleware defined in Nuxt here
In your case you could do your request on /api/user before like that, in a middleware called userLoggedIn for example.
export default function (context) {
// Here we return a Promise in the middleware to make it asynchronous
// Cf doc https://nuxtjs.org/guide/routing#middleware
// So we return a promise that can only be resolved when the function resolve is called
return new Promise(resolve => this.$axios.$get('/api/user'/).then((user) => {
if (!user) {
console.log('NOT LOGGED');
// Do something if not logged, like redirect to /login
return context.redirect('/login');
}
resolve(user);
}));
}
I made a proposition with $axios but of course you can change it. You just need to keep the middleware and the promise to have an asynchronous middleware.
Then on your page waiting for the query, you can add:
export default {
middleware: [
'userLogged',
],
data() {...}
};
I have a problem that when i run below code
cy.contains("Lion").click();
cy.get('rows').each((row) => {
expect(row.text()).to.include("Lion");
});
The assertion above is run before the request that is done after: cy.contains("Lion").click(); is executed which will fail the application. The request is done using graphQL
So first there is no property rows in cy, but even if you added through support.js then cy functions return promises, check this for further info.
you have to use .then (here) to access the cypress values i.e your code will be something like this
cy.contains("Lion").click();
cy.get('rows').then($rows => $rows.each((row) => {
expect(row.text()).to.include("Lion");
}));
I am writing an express application using
NodeJS v8
express (latest version)
After looking at the onHeaders module and finding out how the module rewrites the HTTP head, I wanted to make use of that function of JavaScript.
I wanted to write a small session system using my SQL server. I am aware of the session module from express, but this module is not able to handle the specific tables and customization, I need.
For convenience reasons I wanted the session to be inserted into the request before the controllers and saved after all controllers finished. (e.g. the writeHead method has been called)
My code in the session looks like:
core = async function(req, res, next) {
res.writeHead = hijackHead(res.writeHead); // Hijack the writeHead method to apply our header at the last
}
//[...](Omitted code)
hijackHead = function(writeFunction) {
let fired = false;
return function hackedHead(statusCode) {
if ( fired ) {
return;
}
//[...](Omitted code)
debug("Session data has changed. Writing");
sessionManager.storeSessionData(session.identifier, session).then(() => { // Promise taking ~60ms to resolve
debug("Finished writing...");
callMe(); // Current idea of calling the writeHead of the original res
});
let that = this, // Arguments to apply to the original writeHead
args = arguments
function callMe() {
debug("Finished! Give control to http, statuscode: %i", statusCode);
writeFunction.apply(that, args); // Call the original writeHead from the response
debug("Sent!")
}
} // End of hackedHead
} // End of hijackHead
The core function is being passed to express as a middleware.
Additionally sessionManager.storeSessionData is a Promise storing data and fulfilling after that, taking ~60ms. The Promise has been testes and works perfectly.
When I now make a request using this Controller, the Node net Module returns the error:
TypeError: Invalid data, chunk must be a string or buffer, not object
at Socket.write (net.js:704:11)
at ServerResponse._flushOutput (_http_outgoing.js:842:18)
at ServerResponse._writeRaw (_http_outgoing.js:258:12)
at ServerResponse._send (_http_outgoing.js:237:15)
at write_ (_http_outgoing.js:667:15)
at ServerResponse.end (_http_outgoing.js:751:5)
at Array.write (/usr/lib/node_modules/express/node_modules/finalhandler/index.js:297:9)
at listener (/usr/lib/node_modules/express/node_modules/on-finished/index.js:169:15)
at onFinish (/usr/lib/node_modules/express/node_modules/on-finished/index.js:100:5)
at callback (/usr/lib/node_modules/express/node_modules/ee-first/index.js:55:10)
Since the new function needs about 30ms to react and return the Promise, the function finishes earlier causing Node to crash.
I already tried blocking the Node loop with a while, timeout or even a recursive function. Neither of them worked.
I tries to simplfy the code as much as possible and I hope that I didn't simplify it too much.
Now I am asking if anybody can help me, how to call the writeHead function properly after the Promise has resolved?
The issue with this is, that net.js directly responds to those methods when writeHead has finished. Even though the head has not been written, it tries to write the body.
Instead it is possible to catch the end()method which will await everything and then close the connection.
I working on a frontend app which based on firebase (v4.6.2) and I have a function like this:
function saveSomeData(data) {
return firebase
.database()
.ref("/some/reference")
.set(data)
.then(
() => {
// Success callback is always executed (even in offline mode).
},
reason => {
// Error callback is never executed for some reason :-(
}
);
}
I decided to test app behavior in case of some error (for example in case of disconnect). I expected, that returned promise will be rejected, but it isn't. Firebase documentation says, that this promise will be resolved after synchronization with remote server completed (which sounds reasonable), but looks like it behaves in a different way...
So, the question is: how to force it to reject the promise in case of offline (I don't need all the fancy offline capabilities for sure)?
Firebase is re-establishes a connection when a connection is dropped.
All requests made when a connection is dropped are kept in a queue and sync-ed when a connection is re-established.
Errors leading to a promise rejection include validation errors with keys, errors trying to write to a protected reference such as .info/* amongst many others but not connection errors.
In any case, syncing of update & set operations can be stopped when there is a disconnection by cancelling queued requests for the reference.
Such query will look like so.
function saveSomeData(data) {
const ref = firebase
.database()
.ref("/some/reference");
return ref.set(data)
.then(
() => {
ref.onDisconnect().cancel();
// Success callback is always executed (even in offline mode).
},
reason => {
// Error callback is never executed for some reason :-(
}
);
}
I'm trying to get data out of response but I can't seem to get the result I want.
facebookLogin(): void {
this.fb.login()
.then((res: LoginResponse) => {
this.accessToken = res.authResponse.accessToken;
this.expiresIn = res.authResponse.expiresIn;
this.signedRequest = res.authResponse.signedRequest;
this.userId = res.authResponse.userID;
console.log('Logged In', res, this.accessToken); //works without problem
this.router.navigate(['../other-register']);
})
.catch(this.handleError);
console.log(this.accessToken) //printing 'undefined'
}
Here within then => { }, console.log seems to print the data in res without any problem. I can see data I want but when I console.log outside of then =>{ }, it's giving me undefined.
what am I doing wrong? I need to use data inside response and pass them to other component but I can't seem to figure out what I'm doing wrong.
Can anyone help me? Thanks
This is the expected behavior actually.
this.fb.login() is a Promise. This means that the value of the result/response (res) will not readily be available right when it is called, but it 'promises' that it will have a value once some action is taken or a response is returned and 'then' it will do something. In this case that action would be connecting to the Facebook API and having data returned. This is just like Ajax in jQuery if you have experience with that, Promises are a more evolved version of callbacks.
What is happening is that you function is being executed in this order:
this.fb.login() is called. Doesn't have a value yet so it allows the script to continue.
console.log() is called.
this.fb.login's value is returned and the then() closure is executed.
If you want to know when the value is return or perform a specific action once it is returned you can call a function within .then() or look into observables (RxJS) to notify other parts of your application that login was successful (or wasn't).
Observables Example
Here is one example on Observables, however, I would do more research as there are multiple Subjects to select from, all which have slightly different behavior. Also, this kind of pattern works better in Angular2+ if this is performed in a service, that way other components will be able to access the information provided by Facebook.
import { AsyncSubject } from 'rxjs/AsyncSubject';
// ...
response: AsyncSubject<any> = new AsyncSubject();
facebookLogin(): void {
this.fb.login()
.then((res: LoginResponse) => {
this.response.next(res);
this.response.complete();
this.router.navigate(['../other-register']);
})
.catch(this.handleError);
}
You then retrieve the data from within response like this:
this.response.subscribe(result => {
console.log(result);
})
Pass Data Example
Since you already have a function in the service designed to receive the data, this may be a wiser implementation in your case.
facebookLogin(): void {
this.fb.login()
.then((res: LoginResponse) => {
this.user_service.passData(res.authResponse.accessToken);
this.router.navigate(['../other-register']);
})
.catch(this.handleError);
}