post works with request module but not axios - express

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" }
}
);

Related

Cors error - ngrok & express & axios issue when trying to make POST request to the server

I am experiencing an issue when trying to make POST request to the server.
both frontend and backend are ngrok hosting.
this is the POST request:
export async function createTest(test: any) {
try {
const res = await axios.post(
`${backendDomain}/test`,
{id: test, name: 'test'},
{
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'POST',
},
}
)
const newTest = res.data
return newTest
} catch (error) {
console.log(error)
}
}
this is the backendDomain: https://sd21-23-221-223-216.ngrok.io
Backend:
const corsOptions = {
origin: "https://dz23-12-256-124-663.eu.ngrok.io",
methods: ['GET', 'PUT', 'POST', 'HEAD', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'Origin', 'Access-Control-Allow-Origin'],
credentials: true,
}
app.use(cors(corsOptions))
Error:
Access to XMLHttpRequest at 'https://sd21-23-221-223-216.ngrok.io/test' from origin 'https://dz23-12-256-124-663.eu.ngrok.io' has been blocked by CORS policy:
Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response.
More wierd is that I also have GET request which sometimes work and sometimes not.
any ideas?
You need to add this header param ngrok-skip-browser-warning with any value
Example:
$.ajax({
url: 'https://5120-143-202-253-244.eu.ngrok.io/api',
type: 'GET',
headers: {
"ngrok-skip-browser-warning":"any"
},
success: function (data) {
console.log(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
})
})

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

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);
});

AXIOS POST failed access control check: No 'Access-Control-Allow-Origin' .HTTP status code 405

I don't know what I did wrong and need help.
function loadDoy() {
axios({
method: 'post',
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});
}
You can use 'crossDomain': true at your header of axios post, this is due to cors error. Your browser is making a Preflight Request, which uses the OPTIONS HTTP method. This is to check whether the server will allow the POST request – the 405 status code is sent in the response to the OPTIONS request, not your POST request
In this case, the following is causing the request to be preflighted:
if the Content-Type header has a value other than the following:
application/x-www-form-urlencoded
multipart/form-data
text/plain
The value for the Content-Type header is set to application/json;charset=utf-8 by axios. Using text/plain;charset=utf-8 or text/plain fixes the problem: You may try using like below.
source: App Script sends 405 response when trying to send a POST request
axios({
method: 'post',
headers: {
'crossDomain': true,
//'Content-Type': 'application/json',
'Content-Type': 'text/plain;charset=utf-8',
},
url: apiPostUrl,
data: {
user: "webuser",
password: "m0nk3yb#rz",
layout: "Main Menu"
},
})
.then(function(response) {
this.token = response.data.token;
//if login token works then get records
getRecords();
})
.catch(function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
});

How to send data to server and fetched response using react native application?

I am trying to learn react native application by making a simple login page using api call. Where I will send user name and password to api and it will give me response. But I can't do it. Well I am sharing my code here.....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the way of passing my user name and password to server is wrong. Please give me some idea then I can understand what is wrong here.
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I hope this helps.
You need to Stringify the json data to send request as Post method with Json parameters as you are trying to do...
Here is the example code for how to encode data before requesting for response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Here is the sample code for login :
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
As the commentators before me stated, you simply need to stringify your JSON Body. In general, I' suggest that you incorporate e.g. api sauce into you stack. It is a comprehensive wrapper around the axios library, providing standardized errors and an ok key for quick checks.