http request work in postman but not in browser - http

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: '*'}));

Related

NextJs - Use fetch() to make api call with POST method - always ERR_ABORTED 400

when I try to make api call with fetch() method and request type is POST, then I receive error in console: "POST ... ERR_ABORTED 400 (Bad request)"
btw. I have used 'no-cors' mode because api url is on different domain, I know that this is not best approach. For now I just want to make it to work and later I will deal with CORS issue that I have when mode is not set to 'no-cors'.
const res = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify({
sku: sku
}),
headers: {
'Authorization': 'Bearer ' + jwtToken,
'Content-Type': 'application/json'
},
mode: "no-cors"
});
What can be the cause why fetch() method always returns error, maybe something with the syntax? Both "sku" and "jwtToken" variables are set.
I tried it with postman and everything works fine, but when I try to make that api call inside nextjs then its not working.

Axios network error on Cors Post request with status code 200

I use axios to communicate with my own API (not written in NodeJS).
When I post a non simple request axios always goes directly to the catch block displaying a network error in the console, even with 2 successful Http Requests.
Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
There is also a CORS warning about a missing header
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8080. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
However it is included in the Options Request!
When I add 'Access-Control-Allow-Origin': '*' in the Axios request headers, the warning is gone, but the browser doesn't fire a Post request after the successful Options request.
For the sake of being complete here are the post request headers.
The code:
postForm = () => {
axios.post("http://127.0.0.1:8080/",
myComplexObj, {
headers: {
//'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
timeout: 15000
}
).then(res => {
console.log(res);
alert('success');
})
.catch(function(error) {
//code always end up here
console.log(error);
/*Error: Network Error
Stack trace:
createError#http://localhost:3000/static/js/bundle.js:1634:15
handleError#http://localhost:3000/static/js/bundle.js:1170:14
*/
console.log(error.response); //undefined
console.log(error.response.data); //undefined
}
})
Any help is gladly appreciated.
What I have tried:
Remove the timeout //no change
Remove the Catch block //still no success
Return status code 204 on Options and/or Post requests //no difference
You are confusing because status 200, however, the browser will not allow you to access the response of a CORS request if the Access-Control-Allow-Origin header is missing.
Here are some great articles that explain how CORS works:
https://www.html5rocks.com/en/tutorials/cors/
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Anyway, I think that you are using Django. So, you need add to settings.py:
CORS_ORIGIN_WHITELIST = (
'localhost:8080',
'localhost'
)
Or wherever you have the axios code.

Angular 2 POST Request

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.

I see the response body in chrome developer tools, but unable to retrieve it inside Front End

I am currently working in a project where I need to send a response from grails back end to ReactJs front End. I was able to send the response from grails controller using "response" but unable to extract the response body on the ReactJs side. I tried checking in the following and found null value or undefined.
response.content, response.body
I see the response I sent back from grails in chrome web developer tools "Network" tab. but unable to find out which field of response object actually has it. Any help regarding this will be highly appreciated.
My http request.
post: function(url, item) {
return fetch(baseUrl + url, {
headers: {
'Accept': 'text/plain',
'Content-Type': 'text/plain'
},
method: 'post',
body: item
}).then(function(response) {
alert(response);
return response ;
});
},
grails
response << "there is an error"
Try render 'there is an error'
Or if you need to render JSON:
render [someKey: 'there is an error'] as JSON
To understand how grails controllers and views work read this simple example.
Have you tried content-type: 'application/json'

With Backbone collection's "create", how do I check for errors in the backend?

When I do this:
Comments.create(dat, {
wait:true,
success:function(){
main_alert('Posted successfully', 'success', 3000);
},
error:function(????){
main_alert('Error posting', 'error', 'default');
}
});
I want my server to return an "error" whenever I notice something wrong no the backend. Currently, my server returns a JSON whenever the creation is complete. How does my server return an error? And what would the error argument be?
The parameters that both success and error receive are (model, response, options). Here is the reference. Under response there a property responseText with the text received from the server.

Resources