Angular2 display .NET API validation messages - asp.net

I am transacting .NET API through Angular2(honestly.. 5) I implement server side-model validation using Data Annotations Attributes. As such, the API returns bad request(404) with the validation messages attached:
if (!ModelState.IsValid)
return this.BadRequest(ModelState);
My issue has to do on how to display those messages in my angular view.
My Angular service:
submitForm(formObj: FormDto) {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json; charset=utf-8');
return this.http.post("/api/Forms", JSON.stringify(formObj), { headers })
.map((res: Response) => console.log(res));
//need a .catch here obviously ??????
}
and the way I call the service from the component itself:
submitForm() {
this.formService.submitForm(this.formObj)
.subscribe(res => { console.log(res);
//update this bit to display error messages ?????
});
}
Again, my issue is how to display properly the returned validation error messages coming from the .NET API.

Let's star with the fact that the modelState is coming as an object(key-value pairs). Thus, you can access the object in view by a specific key. You can have a variable in your component and store the modelState object in it.
To the point....
I wouldn't touch the Angular service at all, but the way you subscribe to it in order to separate success and failed callback:
submitForm() {
this.formService.submitForm(this.formObj)
.subscribe((data) => //do what ever on success,
(err) => { this.errors= err.error; });
}
After that, you are able to see your error messages in the view. Something like:
<span class="error-message">{{errors['EmailAddress']}}</span>
Put the line above to every input it's needed but change the key to view the right message. I've done a quick demo and is working.
I hope that helped.

Related

Sending multipart/form-data using GraphQL API in .NetCore

I'm trying to upload the user avatar of .png/jpeg/.jpg file types from angular client to .netCore server application using GraphQL API.
I managed to send the image to be uploaded in a request of content type multipart/form-data from client-side.
But getting a 400 Error from the API server saying the content-type is not supported.
Error message is as follows:
message: "Invalid 'Content-Type' header: non-supported media type.
Must be of 'application/json', 'application/graphql' or 'application/x-www-form-urlencoded'. See: http://graphql.org/learn/serving-over-http/."
I'm trying to implement the mutation like this.
FieldAsync<StringGraphType>(
"testImageUpload",
arguments: new QueryArguments(
new QueryArgument<StringGraphType> { Name = "testArg" },
new QueryArgument<UploadGraphType> { Name = "file" }
),
resolve: async context =>
{
var testArg = context.GetArgument<string>("testArg");
var file = context.GetArgument<IFormFile>("file");
try
{
return await uploaderService().UploadImage(file);
}
catch (Exception e)
{
context.Errors.Add(new ExecutionError("Something happened!"));
return context.Errors;
}
});
I'm using GraphQL.net and GraphQL.Upload.AspNetCore for supporting multipart files.
Sample mutation will be like this:
mutation testImageUpload($testArg: String, $file: Upload) {
fileUpload{
testImageUpload(testArg: $testArg, file: $file)
}
}
Can anybody suggest to me how to make the .NetCore webAPI application accept multipart/form-data.
Any help will be appreciated. Thanks in advance.
I, too, ran into this issue. The answer lies within your Startup.cs file.
First, the reason for which the "Invalid 'Content-Type' header" appears even while using GraphQL.Upload is because (at the time of this answer) the GraphQL.net middleware only checks for the three different Content-Type headers and errors out if none of those match. See GitHub
As for the solution, you haven't shared any of your Startup.cs file so I'm not sure what yours looks like. I'll share the relevant pieces of mine.
You'll need to add the service and the middleware.
The service:
services.AddGraphQLUpload()
.AddGraphQL((options, provider) =>
{
...
});
If you're using a endpoints to map to a middleware, you'll need to add the UseGraphQLUpload middleware, then map your endpoint.
Example:
app.UseGraphQLUpload<YourSchema>("/api/graphql", new
GraphQLUploadOptions {
UserContextFactory = (ctx) => new GraphQlUserContext(ctx.User)
});
app.UseEndpoints(endpoints =>
{
// map HTTP middleware for YourSchema at path api/graphql
endpoints
.MapGraphQL<YourSchema, GraphQLMiddleware<YourSchema>>("api/graphql")
.RequireAuthorization();
...
// Additional endpoints
...
}
Everything else looks fine to me.

Cypress: How to access the body of a POST-request?

Is there a way in Cypress to check the body of a POST-request?
E.g.: I have entered some data in a form, then pressed "Submit".
The form-data is send via POST-request, separated by a blank line from the header-data.
I would like to check the form-data. If all data, which I have entered, are included and if they are correct.
Is that possible with Cypress?
cy.get('#login').then(function (xhr) {
const body = xhr.requestBody;
console.log(xhr);
expect(xhr.method).to.eq('POST');
});
The xhr-object doesn't have the transferred data included.
It should be possible.
describe('Capturing data sent by the form via POST method', () => {
before(() => {
Cypress.config('baseUrl', 'https://www.reddit.com');
cy.server();
cy.route({
method: 'POST',
url: '/login'
}).as('redditLogin');
});
it('should capture the login and password', () => {
cy.visit('/login');
cy.get('#loginUsername').type('username');
cy.get('#loginPassword').type('password');
cy.get('button[type="submit"]').click();
cy.wait('#redditLogin').then(xhr => {
cy.log(xhr.responseBody);
cy.log(xhr.requestBody);
expect(xhr.method).to.eq('POST');
})
});
});
This is how you can inspect your data in Chrome Developer Tool.
You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress.
I was Googling the same problem and somehow landed here before reaching the documentation.
Anyway, have you tried something like:
cy.wait('#login').should((xhr) => {
const body = xhr.request.body
expect(body).to.match(/email/)
})
I haven't tested it out with a multipart/form-data encoded request, but I suspect that you'll also find the request body that way.
Good luck!
It's better to use cy.intercept() in order to spy, stub and assert network requests and responses.
// assert that a request to this route
// was made with a body that included 'user'
cy.wait('#someRoute').its('request.body').should('include', 'user')
// assert that a request to this route
// received a response with HTTP status 500
cy.wait('#someRoute').its('response.statusCode').should('eq', 500)
// assert that a request to this route
// received a response body that includes 'id'
cy.wait('#someRoute').its('response.body').should('include', 'id')
Link to the docs

angular5 how to make asyc request?

In my project i made multiple request to server to get data for single page. I want to make all request asyc. Right now until i get the response from first request,the response of second request is not load.
So basically i just want to achive asyc request and response so one request will not wait for other request to finish.
Right now it's like first come first serve fashion.
But i want from multiple request which request get first response should load first.
this is code of my component
constructor(private _dashboardService: DashboardService) {
this.getLineChart();
this.todayPaymentDetails();
this.todayPaymentMethod();
this.rewardCustomers();
this.getAverageBill();
this.getItemByVolumn();
this.getItemBySales();
}
todayPaymentMethod(id=null){
this.paymentMethodsLoader=0;
this._dashboardService.getTodayPaymentMethod(id).subscribe(res =>{
if(null != res.data && '' != res.data){
this.location = res.data.location;
this.payment_methods = res.data.payment_methods;
}
this.paymentMethodsLoader=1;
});
}
this is my service code:
getTodayTotalPayment(id) : Observable<any> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this._http.get(environment.apiUrl + constants.API_V1 + 'today-total-payment/'+id, options)
.map(res => res.json())
.catch((error: any) => Observable.throw(error.json().error || error));
}
Here shows code for only one request but as shown in constructor i send multiple request at a time.
FIrst it is not a good practise to call function like this in constructor.
For running multiple request or observable together use operators i.e. switchMap etc.
Follow this video link related to event loop in JavaScript this will improve your JavaScript execution , event loop concepts . also explains how asynchronous code executed.
Hope it will help.

Is there a way to be notified when a client has unsubscribe from server sent events?

As I understand when a request to an event emitter on the server arrives, that request is never closed and you only need to res.write() every time you would like to send a message. However is there a way to be notified when the client that performed this request has left? Is there a property on the request object?
suppose I have the following route
app.get('/event',function(req,res){
//set response headers
//how do I check if req object is still active to send a message and perform other actions?
})
The basic sequence of events should be similar in other frameworks, but this example is Grails 3.3.
First set up endpoints to subscribe, and to close the connection.
def index() {
// handler for GET /api/subscribe
rx.stream { Observer observer ->
// This is the Grails event bus. background tasks,
// services and other controllers can post these
// events, CLIENT_HANGUP, SEND_MSG, which are
// just string constants.
eventBus.subscribe(CLIENT_HANGUP) {String msg ->
// Code to handle when the grails event bus
// posts CLIENT_HANGUP
// Do any side effects here, like update your counter
// Close the SSE connection
observer.onCompleted()
return
}
eventBus.subscribe(SEND_MSG) {String msg ->
// Send a Server Sent Event
observer.onNext(rx.respond(msg))
}
}
}
def disconnecting()
{
// handler for GET /api/disconnect
// Post the CLIENT_HANGUP event to the Grails event bus
notify(CLIENT_HANGUP, 'disconnect')
}
Now in the client, you need to arrange to GET /api/disconnect whenever your use-case requires it. Assuming you want to notice when someone navigates away from your page, you could register a function on window.onbeforeunload. This example is using Vue.js and Axios.
window.onbeforeunload = function (e) {
e.preventDefault()
Vue.$http({
method: 'get',
url: 'http://localhost:8080/api/disconnect'
})
.then((response) => { console.log(response) })
.catch(({error}) => { console.log(error) })
}
In the case of Servlet stacks like Grails, I found that I needed to do this even if I had no housekeeping of my own to do when the browser went away. Without it, page reloads were causing IOExceptions on the back end.

Express.js get http method in controller

I am building a registration form (passport-local as authentication, forms as form helper).
Because the registration only knows GET and POST I would like to do the whole handling in one function.
With other words I am searching after something like:
exports.register = function(req, res){
if (req.isPost) {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
The answer was quite easy
exports.register = function(req, res) {
if (req.method == "POST") {
// do form handling
}
res.render('user/registration.html.swig', { form: form.toHTML() });
};
But I searched a long time for this approach in the express guide.
Finally the node documentation has such detailed information:
http://nodejs.org/api/http.html#http_http_request_options_callback
Now you can use a package in npm => "method-override", which provides a middle-ware layer that overrides the "req.method" property.
Basically your client can send a POST request with a modified "req.method", something like /registration/passportID?_method=PUT.
The
?_method=XXXXX
portion is for the middle-ware to identify that this is an undercover PUT request.
The flow is that the client sends a POST req with data to your server side, and the middle-ware translates the req and run the corresponding "app.put..." route.
I think this is a way of compromise. For more info: method-override

Resources