How to call a http request synchronously in angular 5 - javascript

I want to call an http.post() request synchronously and after the response receive want to proceed with other code.
Or just want to hit the server but don't want to wait for the response.

Perhaps I'm just missing something, but that shouldn't be too hard if you're willing to ignore the response. If you're using angular, put somewhere at the top of your file:
import { HttpClient } from '#angular/common/http';
Then, in the constructor, include:
constructor(private http: HttpClient, ...) {
//...
}
Finally, in your code, just include the post request with an empty function after you get the result back:
this.http.post(url, requestBody, options).toPromise().then(() => {}).catch(error => {
console.error("Error: ", error);
});
Hope this helps!

Related

Console log raw data of a failed Axios get request

I would like to make an Axios get request to a private server running Flask.
In case there is an internal error in the back-end it returns an response object and an error code.:
response_object = {
"Success": False,
'error': err.message
}
return response_object, 400
The served response_object should be accessible the front-end (React.js).
axios
.get(`http://127.0.0.1:5000/data`, {
data: null,
headers: { "Content-Type": "application/json" }
})
.then(response => {
console.log(response);
})
.catch(function(error) {
console.log(error.toJSON());
});
I would expect the error to include the response object. If the URL is accessed manually in the browser the error data is visible. If there is no error in the back-end the get requests works properly.
After googling for some time I found some issues that might relate to the mentioned problem. (That is why empty data is passed in the a get request).
https://github.com/axios/axios/issues/86
https://github.com/axios/axios/issues/86
Please note that I am self taught so I might miss something obvious here. Thank you all and all the best.
I'll copy/paste my comment here so other can easily see the answer for the question
if it's a 400 status code that it's throwing (you can confirm by using the Network tab in your browser), it will fall into the catch block, the only concern is the toJSON() call... just do a simple console.log(error.message) to check if you ever get there...
I leave you a simple example so you see the catch in action
more information:
in Axios, the response text is in response.data
if you are receiving a JSON, the response.data will be automatically parsed
you do not need to pass data: null as that's the default behavior, and it's not used in a GET call (you won't pass a body in a GET call)

$request->ajax() returns false on ajax call

I am making a ajax request with axios to a laravel controller, i want to use a middleware to check if the request was made with ajax, but the problem is that when i make an ajax request, the middleware throws false always.
i make the call like this
axios.post('/api/contact/send', {
...
data : data
}).then((response) => {
Do somethings
}).catch(err => {
Do somethings
})
my api routes
Route::namespace('Home')->middleware('IsAjaxRequest')->domain(env('HOST'))->group(function(){
....
Route::post('contact/send','ContactController#postContact');
});
the IsAjaxRequest middleware
if(!$request->ajax()) {
abort(403, 'Unauthorized action.');
}
return $next($request);
and the controller
<?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Events\Home\ContactMail;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactRequest;
class ContactController extends Controller
{
//
public function postContact(ContactRequest $request)
{
$data = $request->all();
event(new ContactMail($request->all()));
return response()->json();
}
}
if i take out the middleware, everything will work fine, the problem is when i check $request->ajax() that return false, i have checked it outside the middleware directly in the controlelr but the result is the same, what's wrong? why return false if the call was made via ajax?
Axios does not send the X-Requested-With header that Laravel looks for to determine if the request is AJAX.
If you ask me you should not use or rely on this header at all but (I guess) for the purposes of easy migration away from jQuery (which does include the header) the basic Laravel boilerplate bootstrap.js has code:
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
which ensures all requests made with Axios get this header, however if you are not using that file you need to run this line in your own script.

how to fetch the data from request body in anguar2

i have created one URL and given to the end-user so when user hit my URL from other module i want to fetch the the data from the request body and and after fetching the data i am passing these data to my service and then validating and getting the response from my service.
but when user click on my URL and passing the data in URL then
I am able to fetch the data from URL like this
ngOnInit() {
this.route.params
.subscribe((params : Params) => {
this.email=params['id'];
});
but I am not able to fetch the data from request body when the user hit my URL so that i can fetch the data from the body and pass it to my service.
I need to fetch the two parameters from the request body.
Please first understand that the code you show is not a request to an api so there is no body.
All you are doing here is looking at the current route that shows in the address bar (ie. the current page of your angular app). There is no request body to fetch data from, only the query string params you can see in the address bar.
In other words, this.route refers to the CURRENT route of your angular app showing in the browser.
If you want to call an API and get data then you need to create a service to do that. For example:
#Injectable()
export class StoriesService {
constructor(private http:Http,private constService :ConstantsService) { }
public getStories()
{
this.http
.get(this.constService.apiBaseUrl + "/Stories")
.subscribe ((data: Response) => console.log(data));
}
}
In this example data is the request body returned by the call to [apiBaseUrl]/stories.
I would advise reading this tutorial.

Handling http 302 redirect responses

I know that http 302 responses are handled directly by the browser, and because of that you cannot acces any of the request properties from your source code. But I am wondering if there is any way of intercepting the 302 redirect response. Let me explain myself:
My Frontend (Angular) makes an http request to A (I intercept the outgoing request)
A responds with 302 Location: B
My Frontend intercepts the 302 response with empty fields, and goes to B
Here I'd like to intercept the response coming from B
This is my Angular http interceptor code:
#Injectable()
export class CasInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('->Interceptor');
console.log(req);
return next.handle(req).map((event: HttpEvent<any>) => {
const response = event as HttpResponseBase;
console.log('<-Interceptor');
console.log(response);
return event;
});
}
}
You should get full header from http response.
{observe:"response"} is the magic parameter of angular http client.
So try this one
this.http
.get<any>(requestURL,{observe:"response"})
.subscribe(
data => {
console.log(data.header); //you will see full header here
console.log(data.url); // you can see redirect url from backend and handle it whatever you want
},
err => {
console.log(err)
}

Matching axios POST request with moxios

Is it possible to use moxios to mock a reply to a POST request that will match not just by URL but also by the POST body? Inspecting the body afterwards would work for me too.
This is what I am doing now. As far as I know there are no method specific stubbing methods:
describe('createCode', function () {
it('should create new code', function () {
moxios.stubRequest(process.env.API_URL + '/games/GM01/codes', {
status: 200
})
})
})
There is a way to inspect the last axios request using moxios:
let request = moxios.requests.mostRecent()
expect(request.config.method).to.equal('post')
expect(JSON.parse(request.config.data)).to.deep.equal(code)
The config object is what's being passed in axios, data is the body of the request.

Categories

Resources