Vue 2 Axios redirection - vuejs2

I am making a put request in my Vue/Laravel app to update an entity. The issue I have is that upon doing a PUT request app automatically calls another request which I didn't initiate and can't find the source of the trigger:
submit () {
axios.defaults.headers.put['Content-Type'] = 'application/json';
axios.defaults.headers.put['Accept'] = 'application/json';
axios.put(this.postMomentUrl, JSON.stringify(this.form))
.then(response => {
window.location.href = location.origin + '/task/' + this.form.task_id;
})
.catch(error => {console.log('New Task creation: ' + error)})
},
after the initial PUT request, program automatically calls another PUT request on whatever is stored in window.location.href?

Related

I don't want to clear cashe and cookies in cypress

I have tried many but have not been successful, please help me with the example. I have put all code here you can also try it on your system.
I am testing registration flow using cypress. and I don't want to clear cache/cookies before each test. can anyone help me?
This is my test file, and the first describe block is to send OTP for entered email. the second one is to create a temporary email and save OTP into a JSON file for letter use. and the third one is for verifying OTP using API. but when I use the same URL and enter an email which OTP verified by API it shows 500 Internal server error
const faker = require("faker");
const firstName = faker.Name.firstName();
const lastName = faker.Name.lastName();
const email = firstName + "#mailinator.com";
describe('My Test Suite', function () {
it('Otp Test', function () {
cy.visit('https://outsized.site/')
cy.get('.css-jqdzg6-commonButtonStyle > canvas', { timeout: 30000 }).click()
cy.get('#email').type(email.toLocaleLowerCase())
cy.get('.ant-btn').click()
cy.fixture('data1').then((profile) => {
profile.FreelancerName = firstName.toLocaleLowerCase()
profile.FreelancerEmail = email.toLocaleLowerCase()
cy.writeFile("cypress/fixtures/data1.json", profile)
cy.wait(2000)
})
})
})
context('My Test Suite', function () {
it('Otp Test', function () {
cy.visit('https://www.mailinator.com/')
cy.fixture("data1.json").then(profile => {
cy.get("#addOverlay").type(profile.FreelancerName)
})
cy.get("#go-to-public").click()
cy.wait(2000)
cy.contains('table tbody tr', 'OTP').click() // find the right email
cy.get('#html_msg_body') // iframe
.its('0.contentDocument.body').should('not.be.empty') // wait for loading
.then(console.log) // works with this but errors without - totally weird
.wait(0)
.find("table > tbody > tr:nth-child(3) > td > h2")
.then($h2 => {
const OTP = $h2.text()
cy.fixture("data1.json").then(profile => {
profile.OTP = OTP
cy.writeFile("cypress/fixtures/data1.json", profile);
})
})
})
})
context('My Test Suite', function () {
it('Otp Test', function () {
cy.fixture('data1').then((profile) => {
cy.request({
method: 'POST',
url: 'https://api.outsized.site/graphql',
headers: {
'Content-Type': 'text/plain'
},
body:
'mutation { verifyEmailOtp(email: "' + profile.FreelancerName + '#mailinator.com", otp: ' + profile.OTP + '){ message } }'
})
})
cy.wait(5000)
cy.fixture("data1.json").then(profile => {
cy.visit("https://outsized.site")
cy.wait(5000)
//cy.visit(profile.url+profile.FreelancerName+"%40"+"mailinator.com")
cy.get('.css-jqdzg6-commonButtonStyle > canvas', { timeout: 30000 }).click()
cy.get('#email').type(profile.FreelancerEmail)
cy.get('.ant-btn').click()
cy.request({
method: 'POST',
url: 'https://api.outsized.site/graphql',
headers: {
'Content-Type': 'text/plain'
},
body:
'mutation { addNewEmail(email: "' + profile.FreelancerName + '#mailinator.com"){ message } }'
})
cy.get('.ant-btn').click()
})
})
})
500 Internal server error get because cypress has clear cache and cookies before each test.
There's a relatively new command cy.session() (docs) that preserves cookies, localStorage, and sessionStorage. Not sure if that includes "cache", in fact I don't know what you refer to there.
The way it works is you can add it into a beforeEach() so it gets called by each test, but it only calls the code inside once (first test), then for subsequent calls it retains and restores the values from the above stores that were set during the first test.
There's an example here Unable to access modal-dialogue in cypress which is simpler than the examples in the official documents.
The basic pattern is worth repeating
Cypress.config('experimentalSessionSupport', true) // set this flag
beforeEach(() => {
cy.session('mySession', () => {
// code that sets cookies, only called once
// thereafter same cookies, localstorage, sessionStorage
// are preserved for future test
})
})
I can't really tell what code you need from your sample above, but I'm sure you know already.

Managing Gcal Response + express and header issue

I'm new to node and banging my head against a wall on what should be a simple node+express+googlecal+pug issue
node/express route accepts requests and calls controller
controller ensures validation of auth and then...
executes a successful gcal function...console.log has the data i need
trying to directly (in controller function) returns "Cannot set headers after they are sent to the client"....why is a call to Gcal API forcing a response back to client?
Trying to make it more micro via individual calls to each function results in same result
What am I missing here?
getcalendars: async function(oAuth2Client, res) {
const calendar = google.calendar({ version: "v3", auth: oAuth2Client });
cal = await calendar.calendarList.list(
{},
(err, result) => {
//console.log("HEADERS SENT1?: "+res.headersSent);
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(JSON.stringify(result));
message2 = JSON.stringify(result)
res.render('schedules', {message2: message2})
return
});
},
EDIT: Calling function
router.route('/dashboard/schedules')
.get(async function(req, res) {
if (req.session.loggedin) {
//x = gcalController.getcalendars(req, res);
token = await gcalController.gettoken(req, res);
isAuth = await gcalController.calauth(token);
listcalendars = await gcalController.getcalendars(isAuth,res);
} else {
res.redirect("/?error=failedAuthentication")
//res.send('Please login to view this page!');
}
});
Can't set headers already sent happens when you're sending a response more than once. Usually you can terminate the function by returning your res.send() call.
It looks like the express middleware that created the res object is sending a response by the time your res.render() gets pulled out of the microtask queue.
Can you show the full code? It seems that this is probably originating in the scope where getcalendars is called.

How to implement silent token refresh with axios request interceptor?

We are implementing a token-based authentication and when a user signs in we generate access and refresh tokens then save that with the timestamp on device so we can later check if the access token is expired or not.
We are currently using axios interceptor before every request and checking if the token is still valid or not with the timestamp we saved earlier when we generated the access and refresh tokens, but when the access token is expired and we are making a request to refresh the token the app goes on an infinite loop and none of the requests go through (both the original and refresh token api requests). you can see my code below:
const instance = axios.create({
baseURL: 'http://localhost:8080'
});
const refreshToken = () => {
return new Promise((resolve, reject) => {
instance
.post('/token/renew')
.then(response => {
resolve('refresh successful');
})
.catch(error => {
reject(Error(`refresh fail: ${error}`));
});
});
};
instance.interceptors.request.use(
async config => {
const timestamp = 1602155221309;
const diffMinutes = Math.floor(Math.abs(Date.now() - timestamp) / 60000);
// if diffMinutes is greater than 30 minutes
if (diffMinutes > 30) {
const tokenResponse = await refreshToken();
return config;
}
return config;
},
error => {
return Promise.reject(error);
}
);
The infinite loop is caused by your interceptor triggering another Axios request on which said interceptor will also run and trigger another Axios request, forever.
A simple solution would be to make the refresh token network request using the default axios instance which doesn't include any interceptors:
const refreshToken = () => {
// You can skip returning a new `Promise` since `axios.post` already returns one.
return axios.post("YOUR_BASE_URL/token/renew");
};
Obviously that also means you'll have to write a bit of logic to send the current refresh token along if that's included in your instance interceptors.

how to remove Authorization on login route using axios and vuejs

After creating an axios instance in the main.js file in my project,i pass the baseURL and also pass authorization header,meaning that the authorization headers will be passed in all http request.i want to remove the authorization when i try to login.
i have tried using interceptors.request to get the login url,then write a condition that if that login url is called it should delete the autorization headers.
This is my instace
const base = axios.create({
baseURL: "https://eelspace.herokuapp.com/api/v1/",
headers: { Authorization: "Token" + " " + localStorage.getItem("token") }
});
this is the part where i get the url of login and then i try to delete that headers
base.interceptors.request.use(request => {
let url = request.url;
if (url === "auth/login/") {
// console.log(base.defaults.headers);
delete base.defaults.headers.common["Authorization"];
}
console.log(url);
return request;
});
After running the code..it still doesn't work

Accessing the response from one GET request within another

I'm working with Vue to interact with an external API on a Drupal website, but in order to do so dynamically per Drupal user, I need to get a token from Drupal first. To do so, I'm trying to do two GET requests. The first gets me a bearer token out of Drupal, and the second uses it to authenticate the third-party API request.
Below is what I'm trying – I'm able to get the token successfully in the first request's response, but not when I try to use it in the header of my second request. If I try hardcoding the token that I see in the console log, it does work, so I know none of that is the issue. It's just that this.jwt['data']['token'] in the second request's headers seems to not pull back the token.
What do I need to adjust in order to access the token from the first response as part of the headers of my second request?
created() {
axios
.get('/jwt/token')
.then(response => {
this.jwt = response
console.log(this.jwt['data']['token']) // this does show what I want to access later
})
},
mounted() {
axios
.get('/comment/doc/' + this.id, {
headers: { Authorization: "Bearer " + this.jwt['data']['token'] } // ...but this doesn't work
})
.then(response => {
this.comments = response
})
},
It's likely the response to the token request has not finished by the time the component mounts, at which point this.jwt is not yet assigned.
I would move the token request into the mounted hook, fetching comments only when the token request succeeds:
export default {
mounted() {
axios
.get('/jwt/token')
.then(tokenResp => {
this.jwt = tokenResp
axios
.get('/comment/doc/' + this.id, {
headers: { Authorization: 'Bearer ' + this.jwt['data']['token'] }
})
.then(commentsResp => {
this.comments = commentsResp
})
})
}
}