Its a very normally requirement that a web page may have multiple API requests.
I have been Inertia.js and this works very good but it lacks a very important feature to make plain XHR requests.
However Inertia.js provides Inertia.reload() but it some cases it's not very useful.
I am looking for something like Inertia::xhr() keeping in mind that I can still use Inertia.js interceptors like onStart, onFinish etc.
Anyone can help to achieve this?
You can do plain XHR requests with Axios (which is already a dependency anyway), or alternatively use the native Fetch api.
From the docs:
Using Inertia to submit forms works great for the vast majority of situations. However, in the event that you need more fine-grain control over the form submission, there's nothing stopping you from making plain xhr or fetch requests instead. Using both approaches in the same application is totally fine!
See also here
If you do a Interia::visists it will cause a full page reload.
If you want to prevent that making a call with axios/fetch makes sense. For example, if you just want to add a comment functionality, you may not want to reload the entire page. If the page is slow, the user will feel the delay when adding the comment.
Only thing you have to take care is CSRF token. If you used axios, it should read the XSRF-TOKEN from cookie automatically.
If you use the fetch api, you would need to manually provide the CRSF token.
Meaning you have to either read it from shared data or from the cookie.
If you add it to shared data, it would look like this:
public function share(Request $request): array
{
$isAdmin = Auth::user() instanceof Admin;
return array_merge(parent::share($request), [
'csrf' => csrf_token(),
'session' => [
'notification' => session('notification'),
],
'auth' => self::share_auth(Auth::user()),
]);
}
and your fetch request would look like this:
fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': usePage().props.value.csrf
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({ name: name}) // body data type must match "Content-Type" header
});
Intertia doesn't support plain XHR request.
But we have written a package that provides very similar APIs as Inertia.
https://github.com/JoBinsJP/formjs
Related
I have an API automation test suite using Cypress and one of the issue I am facing in one of the test is to validate the response headers.
For some reason, I am not able to read the response headers using Cypress.
The code is below
cy.request({
method:'GET',
url:Cypress.env("Authorisationurl")+tokenId+'&decision=allow&acr_values=1',
followRedirect: false,
headers:{
'Accept': "/*"
}
}).then((response) => {
const rbody = (response.body);
cy.log(response.status)
//THIS GOT ASSERTED TO TRUE
expect(response.status).to.equal(302)
//OPTION1
cy.wrap(response.headers['X-Frame-Options']).then(() => {
return response.headers['X-Frame-Options'];
});
//OPTION2
return response.headers['X-Frame-Options']
//OPTION3
return response.headers
})
None of the above options gives me the header information. Infact I am confused with the order of execution too.
This is my output.
for the following code.
const rbody = (response.body);
cy.log(response.status)
cy.log(response)
expect(response.status).to.equal(302)
cy.log(response.headers)
cy.log(response.headers['X-Frame-Options'])
return response.headers['X-Frame-Options']
Also, not very sure what Object{9} indicates. Can anyone please explain what is happening here.
I am aware of Cypress flow of execution and the code is written in then block as a call back function.
Option 3 is very scary as it gives an error
cy.then() failed because you are mixing up async and sync code.
In your callback function you invoked 1 or more cy commands but then returned a synchronous value.
Cypress commands are asynchronous and it doesn't make sense to queue cy commands and yet return a synchronous value.
You likely forgot to properly chain the cy commands using another cy.then().
The value you synchronously returned was: Object{9}
Can anyone please help me here as in what is the correct way of doing it. I know Cypress is very quick and easy to use but to move away from Selenium, we need to make coding easier for developers with meaningful error message. Object{9} is not very helpful.
Also, Do I need to use Cy.log ? As the sequence of prints is not what I have written in the code. Thanks very much for your time on this.
Please use like this:
JSON.parse(JSON.stringify(response.headers))["X-Frame-Options"];
The "mixing async and sync code" message is basically saying you should keep the .then() callback simple.
But you can chain more than one .then() to run the async and sync code separately.
Use an alias to "return" the value. Since cy.request() is asynchronous, you will need to wait for the value and the alias pattern is the most straight-forward way to do this reliably.
WRT Object{9}, it's the result of the way Cypress logs complex objects.
Don't use cy.log() to debug things, use console.log().
cy.request( ... )
.then(response => {
expect(response.status).to.equal(200) // assert some properties
})
.then(response => response.headers) // convert response to response.headers
.as('headers')
cy.get('#headers')
.then(headers => {
console.log(headers)
})
Since this was originally posted a year ago and Cypress has had many versions since then, the behavior may have changed, however this works in Cypress 11.
You can access the response.headers array as you would normally expect, however the casing of the header name was not as expected, Postman reported the header as X-Frame-Options, but Cypress would only allow me to access it if I used a lower-cased version of the header name (x-frame-options).
cy.request({
url: '<Url>',
method: 'GET',
failOnStatusCode: false
})
.then((response) => {
expect(response.status).to.eq(200);
expect(response.headers["x-frame-options"]).to.equal("SameOrigin");
})
.its('body')
.then((response) => {
// Add your response testing here
});
});
This is regarding Filepond & Vue-adapter.
I have a struggle with revert / remove file after it has been uploaded. I run a PHP backend with OpenAPI 3 REST API standard and I need/want to use a dynamic url when revert/delete. I use Vue-adapter.
I use this method to return the uuid after file has been uploade to my example.com/media
process: {
onload: response => {
return JSON.parse(response)['#id']
},
If i use the revert: '/' way to remove, it will send the id as body to /media/, but I need to send it do DELETE /media/uniqueFileId route. I tried some ways with revert and remove but didnt manage to get it to be dynamic. If i use revert as a function, am i supposed to use axios or fetch to make a custom request to my endpoint or is there some other way im missing?
revert: (uniqueFileId, load, error) => {
console.log(uniqueFileId)
error('problems')
load()
}
I've inherited a Node.js web app that uses relies on OAuth. Whenever you visit a page the app ensures you've authenticated. Please note, there no Angular, React, Vue, etc here. Each page is straight up HTML.
I want to test this site using Cypress. My problem is, I'm stuck on the initial redirect from the auth provider. Cypress acknowledge OAuth is a challenge.
commands.js
Cypress.Commands.add('login', (credentials) => {
var settings = {
'clientId':'<id>',
'scope':'<scope-list>',
...
};
var body = `client_id=${settings.clientId}&scope=${settings.scope}...`;
var requestOptions = {
method: 'POST',
url: 'https://login.microsoftonline.com/...',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body
}
cy.request(requestOptions);
});
Then, in my test, I have:
context('Home', () => {
it('Visits Successfully', () => {
cy.login();
cy.title().should('include', 'welcome');
});
});
In the test runner, I see the login POST request is occurring. I confirmed that an access token is being received using a console.log, however, my title is empty. It's like the redirect after OAuth isn't happening in Cypress. However, when I visit the site in the browser, the redirect is happening as expected.
What am I missing?
What you might be missing is confusing between the actual UI flow and the programmatic flow of doing OAuth with a 3rd party website.
What you would want to do is to complete the programmatic login and then send the required parameters to your OAuth callback URL for your app manually in the test code.
an example is given here (though it uses a different grant type it gives you an idea) https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/#Writing-tests-using-Cypress-Login-Command
another issue on the cypress github that deals with a similar problem
https://github.com/cypress-io/cypress/issues/2085
this also might help:
https://github.com/cypress-io/cypress-example-recipes/blob/master/examples/logging-in__single-sign-on/cypress/integration/logging-in-single-sign-on-spec.js
Angular CLI: 7.3.3 | Node: 10.7.0 | OS: linux x64 | Angular: 7.2.6
I need server side pagination, sorting and filtering, my table will get 100.000 records easily.
Project example -> https://github.com/sibelly/angular-with-datatablesnet
This example consumes themoviedb API, it's just for testing, that is not my real scenario. Here in this project, I don't activate the server side option as I said is just for testing the calling to my interceptor, just to prove that with ajax directly the interceptor isn't called.
On my real scenario, I have a Laravel API, which has the methods that expect the pagination, sorting and filtering params, because I need it to be done server side to reach a better performance and usability.
When I call the API endpoint using HttpClient, it calls my error.interceptor.ts normally, but the pagination, sorting and filtering information isn't passing to the URL.
So, I concluded that I need to call it via Ajax when I call using the ajax the params are sent as expected.
But what happens is that the user token expire and I need to redirect to the login page again. And this is done using the interceptors of angular, that is not activated when calling using ajax directly because it is outside angular's scope.
To resume, how can I intercept my ajax calling from datatables.net framework in my angular project?
Or is there another way to make the server side pagination, sorting and filtering?
movie.component.ts
ngOnInit() {
//When calling this method the error.interceptor is activated normally
//this.getMostPopularMovies();
//But when I call direct using the AJAX, the interceptor doesn't work
this.dtOptions = {
ajax: {
url: 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=2ed54a614803785fce2d7fe401cc3b21',
params: {
api_key: this.moviedbService.apiKey
},
dataSrc: 'results'
//type: 'GET',
//headers: {"Authorization": 'Bearer ' + JSON.parse(localStorage.getItem('authUser'))["token"]}
},
columns: [
{ data: 'title' },
{ data: 'release_date' }
]
};
}
getMostPopularMovies(){
this.moviedbService.getMostPopularMovies().
subscribe((movies: any) => {
this.moviesList = movies.results;
console.log("====", movies);
}, (error: any) => {
console.error("Erro-> ", error);
});
}
Thanks, guys o/
I'm using serverless and https://github.com/horike37/serverless-step-functions to try and implement a system that is hit by a user, returns HTML based on a database entry for the params provided and then moves to a second function that writes to the database (without forcing the user to wait).
I think a step function in the right approach but I can't seem to get it to return HTML - it always returns a JSON body with the executionArn and startDate. e.g.
{
"executionArn": "arn:aws:states:us-west-2:.......etc...",
"startDate": 1513831673.779
}
Is it possible to have my html body return? At the moment my lambda function returns a simple h1 tag:
'use strict';
module.exports.requestHandler = (event, context, callback) => {
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html'
},
body: `<h1>Success!</h1>`,
};
callback(null, response);
};
This is the state machine I'm aiming to create.
I would suggest going for a react/angular/vue frontend hosted e.g. on S3/CDN that uses serverless for backend queries only, instead of rendering dynamic HTML through Lambdas. The 'standard' approach allows you to build apps that are much more responsive and can benefit from e.g. CDNs.
See e.g. https://www.slideshare.net/mitocgroup/serverless-microservices-real-life-story-of-a-web-app-that-uses-angularjs-aws-lambda-and-more or https://serverless-stack.com/