Angular 2 POST Request - http

While doing the POST request in Angular 2, I am getting:
"EXCEPTION: Response with status: 404 Not Found for URL:" .
However, while accessing the URL directly, I am getting the response page.
Also in my backend code, I can see my data getting passed from client side to server side:
Response_body: "{"Message":"Not able to add Language = A"}"
headers: Headersok: false
status: 404
statusText: "Not Found"
type: 2
url: "http://localhost:1109/api/Language/AddLanguage"
onSubmit(val){
console.log(val);
this.languageService.testPost(val)
.subscribe(
(res:response) => console.log(res);
);
}
testPost(newVal) : Observable<any>{
let body = JSON.stringify(newVal);
console.log(body);
let headers = new Headers({'Content-Type' : 'application/json'});
let options = new RequestOptions({headers : headers});
return this.http.post(this.logUrl,body,options)
.map((res : Response) => res.json());
}

Yes Rachit,I think you are correct.While Debugging,In my Server side Code I found an Exception mentioning Too many Arguments while saving Data To Database.
There's the culprit I believe, this error generally occurs if you supply more than required params to an SP. So in your DB implementation if you are using SP(s) kindly check them one by one which one is supplying extra parameters. And if nothing else is the problem you should have this issue resolved.

Related

"Handler crashed with error runtime error: invalid memory address or nil pointer dereference", but POSTMAN is ok! Why this happens?

I work with vue and go for frontend and backend respectively. I send post request to my server and get 403 error code message(notAllowed). But in postman I get the objects and is fine.
Vue and Vuex
My axios post request:
const response = await this.$axios.post(`http://localhost:8000/v1/org/${params.organization}/kkms/${params.kkm}/closeShift`,{
headers : {
'token' : this.state.token.value
}});
I know I should also use other properties like 'Content-Type' and etc in headers, but know it works well with only "token" property in the other requests. I want to know whether problem in backend or frontend?
It seems you have a mistake in the axios request.
You are receiving a 403, that means you are not authorized (or sometimes something else, check the comments in the question and down here ).
As can be found in axios docs, the post request looks like this:
axios.post(url[, data[, config]]).
It accepts the config (so the headers) as THIRD parameter, while you are setting it as second parameter. Add an empty FormData object as second param, and just shift your config to the third param.
const fakeData = new FormData();
const response = await this.$axios.post(`http://localhost:8000/v1/org/${params.organization}/kkms/${params.kkm}/closeShift`,
fakeData,
{
headers : {
'token' : this.state.token.value
}
});

http request work in postman but not in browser

I am able to send post and get request from postman but when i actually send that request from browser it is not able to fetch records and in console shows error "body: {error: "Collection 'undefined' not found"}".
tried for both Get and Post requests they both provide the data in response in POSTMAN, but in browser it does not work.shows error "body: {error: "Collection 'undefined' not found"}".
in same project at different place i am also using in-memory-data-base, to which i am able to make /GETRequest and recieve the data in response.
homepage.ts:=============
public AllItem: AllItems[] ;
getAllItems(): void {
console.log('AA');
this.itemService.getAllItems() //(this.AllItems)
.subscribe(AllItem => this.AllItem = AllItem );
console.log(this.AllItem);
console.log('EE');
}
item.Service.ts:===============
private itemsUrl = 'api/items'; // URL to web api
private allItemsUrl = 'http://*************.azurewebsites.net/items';
getAllItems(): Observable<AllItems[]>{
console.log('CC');
return this.http.get<AllItems[]>(this.allItemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<AllItems[]>('getHeroes', []))
);
}
// this get request work properly and gives response data from in-memoery-db
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.itemsUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Item[]>('getHeroes', []))
);
}
in POSTMAN it gives data as
{
"items": [
{
"category": "Drink",
"item": "Coffee",
"price": "5$"
}]
}
in Browser console
core.js:15724 ERROR
body: {…}, url: "http://**********.azurewebsites.net/items", headers: HttpHeaders, status: 404, statusText: "Not Found"}
body: {error: "Collection 'undefined' not found"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
status: 404
statusText: "Not Found"
url: "http://*************.azurewebsites.net/items"
__proto__: Object
Got the solution for this, Actually i was using in-memory-web-api at some other places in same project,
Not found collection error suggest that you have used angular-in-memory-web-api before. You need to remove everything related to that from your project, so that you are able to use external api and db.
"InMemoryWebApiModule.forRoot(InMemoryDataService)"
Angular in-memory-web-api, it replaces the HttpClient module's HttpBackend SO it needs to be removed first before using actual server and DB
After this i faced another issue that Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
For this we need to use following in our node server in Azure.
var cors = require('cors');
app.use(cors({origin: '*'}));

How to access Response cookies in angular2?

I'm trying to access this cookies (the response ones):
When I open the request in the chrome debug tools in the network section I can clearly see that the cookies are present, but how can I access those values from my code? I've never worked with cookies before and I don't know what to do to "extract" them... I'm working on a Ionic2 project using Http.
I've read that the allowCredentials: true header has to be sent but that didn't work...
Here's the request/response details:
Here's the service:
public callLogin(service_guid: string, pos_guid: string, login_data: Object) {
return this.http.post(
this.url + service_guid + "/" + pos_guid + "/ack",
login_data,
{withCredentials: true}
)
.map(response => response.headers);
}
And the caller:
this.__posService.callLogin(login_data.service_guid, login_data.pos_guid, {"password": data.password})
.subscribe(
res => {
console.log("Success:");
console.log(res.get("apsession"); // this returns undefined
},
err => {
console.log("Error:");
}
);
When I try to access the cookie from the header it returns undefined. What am I doing wrong here?
The name of the response header you are trying to get is actually Set-Cookie not apsession. So if you did something like res.get("set-cookie") it would return the first header that matched that name. Since you have more than 1, you could do:
let headers: Headers = res.headers;
headers.getAll('set-cookie');
which returns a list of all headers with that name. You could find apsession in there probably.
See:
https://angular.io/docs/ts/latest/api/http/index/Headers-class.html
https://developer.mozilla.org/en-US/docs/Web/API/Response/headers
https://developer.mozilla.org/en-US/docs/Web/API/Headers

Angular 2 http service. Get detailed error information

Executing Angular2 http call to the offline server doesn't provide much info in it's "error response" object I'm getting in the Observable's .catch(error) operator or subscription error delegate (they are both share the same info actually). But as you can see on the screen shot of the console there's actual error was displayed by zone.js somehow.
So, how can I get this specific error info (net::ERR_CONNECTION_REFUSED)?
Thanks.
Whenever server do not respond, response.status will be always equal to 0 (zero)
{
type: 3, //ResponseType.Error
status: 0, // problem connecting endpoint
}
Also note, when you are performing CORS request, but origin (url in browser) is not authorized (not in allowed list of host names configured in remote endpoint) the response would be similar to above, with exception to type attribute which will be equal to 4 = ResponseType.Opaque...
This means, connection was made, but for instance, OPTIONS request returned with headers which do not contain origin or HTTPS request was performed from HTTP origin.
You can handle the error messages so they are easier to read. This can definitely be expanded on too:
public Get() {
return this.http.get(this.URL).map(this.extractData)
.catch(this.handleError);
}
public extractData(res: Response) {
let body = res.json();
return body || {};
}
public handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
Check out this part of the docs on error handling.
Without digging in the code, my expectation is that if the server is unreachable, then no response can be returned from the server. Therefore the Response object remains its initialized state.

Angular2 : detect error from HTTP post

I cannot interecept error from http post
a part of my mservice (http post method)
addApplicationLink(applicationLink: ApplicationLink){
let body = JSON.stringify(applicationLink);
let requestHeaders = new Headers();
var headers = new Headers();
headers.set('Content-Type', ['application/json; charset=utf-8']);
let reqoptions = new RequestOptions({
headers: headers
});
return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,{headers: headers});
in my component :
addApplicationLink() {
//todo
this.addNewLink = false;
/* check if must be done after call real rest service */
//this.applicationLinks.push(this.applicationLinkAdd);
this._applicationLinkService.addApplicationLink(this.applicationLinkAdd)
.subscribe(data => {
this.applicationLinks.push(this.applicationLinkAdd)
},
error => {
// handle error
console.error('this an erreor ' + error.status)
}
)
When user tries to add two same applicationlinks , the backend returns an error 409
But when I execute , error.status displays 200 in browser console
I see also in browser console
XMLHttpRequest cannot load http://localhost:7001...... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 409.
rem : Http post is made with json , thus there is a prefligth call
Have you an idea to intercept error 409 ?
In fact, your server doesn't send back the CORS header (Access-Control-Allow-Origin' header is missing). This prevent the browser from providing the actual 409 error to the Angular2 application within the browser.
You need to fix first the problem on the server and you will be able to see this 409 error.
For more details about how CORS works, you could have a look at this article:
http://restlet.com/blog/2015/12/15/understanding-and-using-cors/

Resources