HttpClient or Http POST with header request not hitting to the server - angular5

I'm trying to issue an http request to validate user and in response i need to get token issued by the server.
this ajax call working fine
$.ajax({
url: '/token',
'data': JSON.stringify({ Id: "test", Password: "test" }),
'type': 'POST',
'processData': false,
'contentType': 'application/json',
success: function (response) {
console.log("token =" + response);
},
});
But i need it in angular so i tried below two methods but none of them worked.
1st
let header = new Headers({ 'Content-Type': 'application/json', 'processData': false});
let options = new RequestOptions({ headers: header });
this.http.post('/token', JSON.stringify({ Id: "test", Password: "test" }), options)
.map(response => {
debugger;
console.log("token =" + response);
});
2nd
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
observe: 'response'
});
what is wrong with them.
I am using Dotnet Core 2.1 and angular 5
Please help me to solve this issue.

Your methods are observables.
In order to send the request and get the result, you need to subscribe to them.
This is an example of the 2nd method.
this.httpClient.post<any>("/token",
{ 'Id': "test", 'Password': "test" },
{
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}).subscribe(response => {
console.log("token =" + response);
});

Related

Error in API response saying required parameters React native

When I call API I am getting below error in response. please find below is code and error message.
TEST RESPONSE:
{
"responseData": {"limit": ["Limit is required"],
"module_type": ["Module type required"],
"section": ["section value \"liveability || investment || recommend\" is required"],
"skip": ["Skip is required"]
}
Implemented code:
fetch( 'https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
Try this way
import FormData from 'FormData';
...
var data = new FormData();
data.append("skip", "0");
data.append("module_type", "buy");
....
fetch('YOUR_URL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
})
.then((response) => response.json())
.then((responseJson) => {
console.log('response object:',responseJson)
})
.catch((error) => {
console.error(error);
});
Sometimes when you work with REST API call you have to work with correct headers.
In your case I suppose your are missing two important headers required to activate a good communication between client and servers:
accept
content-type
Please review your code based on this one:
fetch('https://api.dotcomkart.com/api/homePagePropertyList?', {
method: 'POST',
headers: {
"accept": "application/json",
"content-type": "application/json"
},
body: JSON.stringify({
skip: 0,
limit: 10,
module_type:'buy',
section: 'liveability'
}),
})
I think the server is returning "missing" parameters because is not able to understand the type of content. With Content-Type you should be able to instruct the server on how to parse your data.

my react-native app fail to send body in POST request to backend url

As i am trying to send my data in form of body in backed url as in backed i have made something if it dont receive body it will send sucess: false, msg: haven't received body else sucess: true, msg: jwt token as if i make request from post man with same data it's working but sending via. native app it fails to send.. any help will be helpfull
As 1st request is from postman and 2nd from my app
const handleLogin = (Enrno, Pass) => {
setError(null);
setIsLoaded(false);
setItems([]);
fetch(config.url + "/login", {
method: "POST",
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
},
body : JSON.stringify({
"enrno": Enrno,
"password" : Pass
})
})
.then((res) => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
alert(items[0].msg);
},
(error) => {
setIsLoaded(true);
setError(error);
}
);
};
I think you need to put these to headers, not header.
Accept : 'application/json',
'Content-Type' : 'application/json'
So, it should look like this.
fetch(config.url + "/login", {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
enrno: Enrno,
password : Pass
})
})

Vuejs: axios; Passing custom header in POST method

We are making an axios POST call from VueJs, need to pass a custom header. The way it is coded now, the custom header is not getting passed to the server script, other headers are getting passed. Please let me know what I might be doing wrong. Appreciate your help.
axios({
method: 'post',
url: urltocall,
data: strjson,
config: {
headers: {
'Access-Control-Allow-Origin': 'http://localhost:1337',
'Accept': 'application/json',
'Content-Type': 'application/json',
'username': 'test1'
}
}
})
.then(function (response) {
}
The headers object should not be put into a "config" object.
It's just...
axios({
method: 'post',
url: urltocall,
{
headers: {
....
Try doing it like this:
axios
.post(urltocall, myDataAsJSON, {
headers: {
"Access-Control-Allow-Origin": "http://localhost:1337",
"Accept": "application/json",
"Content-Type": "application/json",
"username": "test1"
}
})
.then(response => {
console.log("Success: " + response.data);
})
.catch(error => {
console.log("Error: " + error.response.data);
});
By the way, based on your 'Content-Type': 'application/json',, I know you're trying to send a JSON object, but where/what is this object?
Also, refer to the Full documentation for more information.

post works with request module but not axios

Burned two hours of my life on this and wondering if fresh eyes can help.
I am attempting to contact auth0 to get access token for the management API.
The provide sample code, using request module, which works perfectly (I have replaced the key/secret values):
var request = require("request");
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"myID","client_secret":"mySecret","audience":"https://dev-wedegpdh.auth0.com/api/v2/","grant_type":"client_credentials"}' };
request(options, function (error, response, body) {
if (error) throw new Error(error);
res.json(JSON.parse(response.body).access_token)
});
I have my ID and Secret stored in .env file, so was able to adjust to this, which also works fine:
var options = { method: 'POST',
url: 'https://dev-wedegpdh.auth0.com/oauth/token',
headers: { 'content-type': 'application/json' },
body:
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'})
}
request(options, function (error, response, body) {
if (error) throw new Error(error)
res.json(JSON.parse(response.body).access_token)
})
I try to make the exact same request using axios and I receive 404 error:
let response = await axios.post(
'https://dev-wedegpdh.auth0.com/api/v2/oauth/token',
JSON.stringify({
grant_type: 'client_credentials',
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: 'https://dev-wedegpdh.auth0.com/api/v2/'
}),
{
headers: {'content-type': 'application/json'},
}
)
I have tried several different formats or configurations for the post function including those found
here and here etc.
Anyone see what I am doing wrong???
In axios post body, you need to send data as JSON, no need to use JSON.stringify.
let response = await axios.post(
"https://dev-wedegpdh.auth0.com/api/v2/oauth/token",
{
grant_type: "client_credentials",
client_id: process.env.auth0AppKey,
client_secret: process.env.auth0AppSecret,
audience: "https://dev-wedegpdh.auth0.com/api/v2/"
},
{
headers: { "content-type": "application/json" }
}
);

How to get access token from api in react native

I am using react native and i want to get the access token from api which is created in django using oAuth 2 authentication
i am passing all the details which are required but i do not know why i am getting error of unsupported grant type
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
'scope': 'read Write'
})
})
.then((response) => response) <----tried response.json() but giving same error of grant type
.then((responseData) => {
console.log(responseData);
})
My expected result is i want access token should display
and what i am getting is
Response {type: "default", status: 400, ok: false, statusText: undefined, headers: Headers, …}
headers: Headers {map: {…}}
ok: false
status: 400
statusText: undefined
type: "default"
url: "http://MyUrl"
_bodyInit: "{"error": "unsupported_grant_type"}"
_bodyText: "{"error": "unsupported_grant_type"}"
__proto__: Object
please help
thanks in advance
tried response.json() but giving same error of grant type - this is answer from Your oauth server.
response.json() transform your response data into json decoded string.
Change Your code to this:
let formData = new FormData();
formData.append('grant_type', 'password');
formData.append('username', 'MyUserNameSettedInApi');
formData.append('password', 'PasswordSettedInApi');
formData.append('client_id', 'MyClientId');
formData.append('client_secret', 'MyClientSecret');
formData.append('scope', 'read Write');
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formData
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
});
Install qs library
npm install qs
Import it in your app and then you'll be able to send it.
Use qs.stringify as shown below
fetch('http://localhost:8888/o/token',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;'
},
body: qs.stringify({
'grant_type': 'password',
'username': 'MyUserNameSettedInApi',
'password': 'PasswordSettedInApi',
'client_id': 'MyClientId',
'client_secret': 'MyClientSecret',
})
})
I also got that same issue of "{"error": "unsupported_grant_type"}" for that, I just pass all the body parameters directly without using JSON.stringify({}); It works for me, find the example code below.
body: 'grant_type=password&username=MyUserName&password=MyPassword'
you need to update the body section only.
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'grant_type=password&username=MyUserName&password=MyPassword'
})
.then(res => res.json())
.then(token => console.log(token))
.catch(err => console.error(err));
Hope this will help you.