Can't send an HTTP POST request in Ionic 3 / Angular 5 - javascript

I'm trying to send a post request from my Ionic 3 (Angular 5) app to my REST api, but I'm getting HTTP 404 (Not found) or HTTP 400 (Bad request).
When I send the post request using Postman it is successful. And also, my GET request in Ionic 3 app works successfully. You can see success request below, it hasn't an Authorization:
Here is my request method:
sendConfirmationCode() {
let mybody = new FormData();
mybody.append('msisdn', '1234567');
let myheaders = new HttpHeaders({
'Content-Type': 'application/json'
});
this.http.post('http://mydomain/methodname', mybody, {headers: myheaders})
.subscribe(data => {
console.log(JSON.stringify(data));
}, error => {
console.log(JSON.stringify(error));
})
}
With headers I get HTTP 404 (Not found) but without HTTP 400 (Bad request). So, I tried different body objects with and without using headers. Here is my usings instead of FormData body object:
let mybody= new HttpParams();
mybody.append('msisdn', '1234567');
-----
let mybody= new URLSearchParams()
mybody.append('msisdn', '1234567');
-----
//SubscriberDataInput is my class for to use as input body model of api's method
let mybody = new SubscriberDataInput();
mybody.msisdn = '1234567';
-----
let mybody = JSON.stringify({ "msisdn": "1234567" });
And tried these cases for sending header instead of above header:
let Options = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
-----
let headers = { 'Content-Type': 'application/json' }
None of them works successfully. Can you please tell the right way?

I found the solution. The problem was my RESTful api prevents ajax post requests. This is a solution in Asp.Net WebApi 2 which related Cors:
Add a constant into Startup class of Startup.cs :
private const string DefaultCorsPolicyName = "localhost";
Add Cors into ConfigureServices method of Startup class:
services.AddCors(options =>
{
options.AddPolicy(DefaultCorsPolicyName, builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
Enable Cors in Configure method of Startup class:
app.UseCors(DefaultCorsPolicyName); //Enable CORS!
Delete first custom header in web.config:
<add name="Access-Control-Allow-Origin" value="*"/>

Related

Invalid request method DELETE using fetch

vanilla JS here, trying to use fetch to delete a resource via an api - getting the following error: "Invalid request method DELETE" - I'm able to Postman / curl the same endpoint without any problems and the status code upon completion is 204 in those cases. Any idea what I'm doing wrong here?
function btnTrash(e) {
var uuid = this.parentNode.parentNode.parentNode.id
var url = "http://10.10.10.10:8080/api/v1/delete/" + uuid
fetch(url, {
method: 'DELETE',
mode: 'no-cors'
});
}
Edit: Managed to solve this - I wasn't setting the allowed methods on the backend "Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE") and finally removing mode: no-cors.
Keeping in mind that removing mode: no-cors only works because I'm setting the access-control-allow-origin to "*" on the response.
function btnTrash(e) {
var uuid = this.parentNode.parentNode.parentNode.id
var url = "http://192.168.0.16:8080/api/v1/delete/" + uuid
fetch(url, {
method: 'DELETE',
})
.then(response => {
if (response.status == 204){
// do something
}
})
}

Bad request response to fetch REST API

I have built an API and app that uses that API. When I POST method via Postman, it works fine, but when I try fetching it via app, I get a bad request 400 status response. What am I doing wrong?
Here is my JavaScript code:
const myForm = document.getElementById('loginForm');
myForm.addEventListener('submit', function(e) {
e.preventDefault();
const url = 'https://thawing-peak-69345.herokuapp.com/api/auth';
const myHeaders = new Headers();
myHeaders.append('Accept', 'application/json, text/html, */* ');
myHeaders.append('Content-Type', 'application/json, charset=utf-8')
const formData = {
email: this.email.value,
password: this.password.value
};
console.log(formData);
const fetchOptions = {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: myHeaders,
body: JSON.stringify(formData)
};
fetch(url, fetchOptions)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
})
Request
Response
Headers request:
Headers response:
You said:
mode: 'no-cors',
This is a declaration that you are not doing anything that requires permission be granted with CORS. If you try to do anything that does need permission, it will be silently ignored.
myHeaders.append( 'Content-Type', 'application/json, charset=utf-8')
Setting the Content-Type header to a value not supported by the HTML form element's type attribute requires permission from CORS. application/json is not such a value.
Consequently, the request is sent as text/plain.
Since it isn't marked as being JSON, the server throws a 400 error.
You need to:
Remove mode: 'no-cors',
Make sure that the service you are making the request to will use CORS to grant you permission (or to use a service on the same origin as the request).

Angular 4 JWT token shows "401 unauthorized"

I've seen similar threads to this issue, but I had no luck solving it.
I'm trying to access my .net core controller "GET" using angular post.
getAll() {
return this.http.get('api/Users/GetAll', this.jwt()).map((response: Response) => response.json());
}
I'm getting this error :
401 Unauthorized
jwt code :
private jwt() {
// create authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
if (currentUser && currentUser.token) {
let headers = new Headers({ 'Content-Type': 'application/json' });
headers.append('Authorization', 'Bearer ' + currentUser.token)
return new RequestOptions({ headers: headers });
}
}
currentUser.token consist a valid token, I can access it via console.log, etc.
What am I doing wrong?

Token is not being set while calling API in angular 4

i'm facing the issue that when i set header i'm unable to send the token to the API.one more strange issue is that when i see in my network log, i can see method getting converted to 'OPTION', also my 'Token' is not being sent. see below Error :
i have tried to find out all the ways but nothing worked for me, can anyone help here.
Reffered questions :
Using http rest apis with angular 2
Angular2 OPTIONS method sent when asking for http.GET
My code :
//set token for Authorization
setHeaders() {
var token = this.localStorageService.getToken();
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Authorization', token);
this.options = new RequestOptions({ headers: headers });
}
//function
getMaintenanceType() {
this.setHeaders();
return this.http.get(this.url_Configuration.maintenancetype, this.options)
.map(res => res.json())
}
Please try to use below solution, it will work.
Set Header with the request :
Create a method setHeader :
setHeader(): RequestOptions {
let headers = new Headers()
headers.append('Accept', 'application/json');
headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers });
return options;
}
And then Use it :
this.http.get(this.baseURL + url, this.setHeader()).map(res => res.json());
I see that you are having Error Code 403. By Any chance, is your server running on a different platform like 'apache, JBOSS, ... etc' and your UI application is on different. If that is the case, You need to implement CORS support to your server, and I can help you with it, once you confirm the server environment.
As of now, I see a couple of things that can be changed in your code, for starters, and this might help too:
headers ;
headers = new Headers ({ 'Content-Type': 'application/json' });
this.headers.append('Accept', 'application/json');
this.headers.append("X-Auth-Token", this.accesToken);
let options = new RequestOptions({ headers: headers, method: 'get' });

Error: The Content-Range header is missing in the HTTP Response

I am setting up admin on rest, and now I am getting this error when I try to fetch data, even though I receive all the data needed from the server:
The Content-Range header is missing in the HTTP Response. The simple REST client expects responses for lists of resources to contain this header with the total number of results to build the pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Expose-Headers header?
Is there a way to solve it without making changes to the API? I was doing authorization based on the tutorial, here is my app.js:
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${"token"}`);
return fetchUtils.fetchJson(url, options);
}
const restClient = simpleRestClient('https://mywebsite.com', httpClient);
const App = () => (
<Admin restClient={restClient} authClient={authClient}>
<Resource name="posts" list={PostList} edit={PostEdit} create={PostCreate}/>
<Resource name="users" list={UserList}/>
</Admin>
);
The issue is not on the React-App but rather your REST server.
In my case, I was using the SimpleRestClient and in their documentation it reads
import simpleRestProvider from 'ra-data-simple-rest';
Note: The simple REST client expects the API to include a
Content-Range header in the response to GET_LIST calls. The value must
be the total number of resources in the collection. This allows
admin-on-rest to know how many pages of resources there are in total,
and build the pagination controls.
Content-Range: posts 0-24/319 If your API is on another domain as the
JS code, you’ll need to whitelist this header with an
Access-Control-Expose-Headers CORS header.
Access-Control-Expose-Headers: Content-Range
So, from your server/the REST server it has to return(include in response) two headers
Access-Control-Expose-Headers: Content-Range
Content-Range: posts 0-24/319
In my flask-server here's what i did
Add the 'content-range' header in your responses.
response.headers.add( 'Access-Control-Expose-Headers', 'Content-Range')
Add the header 'Content-Range' and assign it a range value(usually in bytes)
response.headers.add('Content-Range','bytes : 0-9/*')
Finally: I noticed that when either of the headers is omitted from your response you'd get the same error
Error: The Content-Range header is missing in the HTTP Response
Ensure your server returns these headers
'Access-Control-Expose-Headers', 'Content-Range'
or
'Content-Range','bytes : 0-9/*'
I hope this helps as it's my ever first response to a SO question
If you are using fastapi with react admin you need to add this to route
response.headers['X-Total-Count'] = '30'
response.headers['Access-Control-Expose-Headers'] = 'Content-Range'
``
You need to add custom headers to your requests, you can just wrap the fetchJson() call inside your own function:
For instance:
import { fetchUtils, Admin, Resource } from 'react-admin';
import simpleRestProvider from 'ra-data-simple-rest';
const fetchJson = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
// add your own headers here
options.headers.set('X-Custom-Header', 'foobar');
return fetchUtils.fetchJson(url, options);
}
const dataProvider = simpleRestProvider('http://path.to.my.api/', fetchJson);
const App = () => (
<Admin dataProvider={dataProvider}>
<Resource name="posts" list={PostList} />
</Admin>
);
For the most common usage of custom headers is for authentication. fetchJson has built-on support for the Authorization token header:
const fetchJson = (url, options = {}) => {
options.user = {
authenticated: true,
token: 'SRTRDFVESGNJYTUKTYTHRG'
};
return fetchUtils.fetchJson(url, options);
};
const dataProvider = simpleRestProvider('http://path.to.my.api/', fetchJson);
Now all the requests to the REST API will contain the Authorization: SRTRDFVESGNJYTUKTYTHRG header.

Categories

Resources