I am sending the clientid variable in my React-native project. I am sending the body using the post method when posting.But now the clientid variable is not going to php, it sends a null value.
React-Native Code
let rspNew = await get3dNumber({
clientid: "500300000",
...
})
export function get3dNumber(CART){
return fetch(`http://...php`,{
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
redirect:'follow',
body:JSON.stringify(CART)
})
}
PHP CODE
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
$json = json_decode(file_get_contents('php://input'), true);
$myArray = array();
$myArray['clientid'] = $json['clientid'];
?>
Related
In postman is a section where you can put or set a header. But how do i set it but in the navigator, that lasts over time through requests to different routes?
I´ve already tried setting a header, from the backend with differents methods like, and none of both worked:
res.header('x-token', jwt)
Or like
res.set('x-token', jwt)
And from the frontend i already tried with this methods and it didn´t work either:
const data = {id_token};
//let myHeaders = new Headers();
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
})
.then(resp => resp.json())
.then(({jwt}) => {
if (jwt) {
localStorage.setItem('x-token', jwt);
//None of both worked
//myHeaders.append('x-token', jwt);
//myHeaders.set('x-token', jwt);
}
})
.catch(error => console.error('Error:', error))
This is the header that i wanna send to the different routes:
https://i.stack.imgur.com/ueoxu.png
You can set the x-token header from your screen shot like this:
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json',
'x-token': 'eyJhbGciOiJIUzl.....'
}
}).then(...).catch(...)
What code can I use to access a bearer token that's been stored in localStorage?
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'.
Authorization: ???
}
});
I'm having trouble sending auth headers using a axios Service. When I hardcode the existing bearer token it works, but how can I dynamically access that for each user as it changes?
This is what worked! Thanks to DigitalDrifter for showing me the getItem function in localStorage.
I've been storing the bearer token in 'user' state, so I retrieved the object, parsed it, then inserted it into the Authorization header.
const user = JSON.parse(localStorage.getItem('user'));
const token = user.token;
const apiClient = axios.create({
baseURL: 'http://localhost:5000/api/v1',
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
});
A request interceptor can be used to set the Authorization header prior to each outgoing request.
// Add a request interceptor
axios.interceptors.request.use(function (config) {
let token = localStorage.getItem('bearer_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
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" }
}
);
I am building android app using react native expo integrated with redux. The API is called using fetch method, but always the cached result is displayed. The server did not receive the request second time. I tried disabling cache with the following code.
export const mymails = (token) => {
return fetch(
API_URL+'?random_number='+ new Date().getTime(), {
method: 'GET',
headers: getHeaders(token)
})
.then(response => response.json());
};
getHeaders = (token) => {
return {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token='+token,
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': 0
};
}
When I call the API through Postman client I see different result(not cached). I tried adding random number as parameter and setting cache control headers, but still returning cached result. Is there is anything else I could try.
Thanks
There must be a problem with how are you setting up the headers for fetching request.
Try with following,
You can follow the link for the same in the Official Fetch API
const mymails = (token) => {
var myHeaders = new Headers();
myHeaders.set('Accept', 'application/json');
myHeaders.set('Content-Type', 'application/json');
myHeaders.set('Authorization', 'Token token=' + String(token));
myHeaders.set('Cache-Control', 'no-cache');
myHeaders.set('Pragma', 'no-cache');
myHeaders.set('Expires', '0');
return fetch(
API_URL + '?random_number=' + new Date().getTime(), {
method: 'GET',
headers: myHeaders
})
.then(response => response.json());
};
let headers = new Headers();
headers.append('Accept', '*/*');
headers.append('Content-Type', 'multipart/form-data');
let payload = await this.http.fetch(path, {
method: 'post',
body: item,
headers: headers
}).then(response => response.json())
.catch(err => err);
I am creating this piece of code to post a file to the server. When making the request this converts the header from Content-Type to content-type, Accept to accept, and this is causing me problems, I am using Aurelia + TypeScript.
Any ideas to avoid this behavior?