axios https call now working, why it always takes to https? - reactjs

i am working on react axios, i run the axios call, you can see i setup the http api call, but when i run the code, it call https api, can anyone please help me why it is doing that ? any help will be really appreciated.
await axios({
method: 'Post',
//url: `${helper.ApiUrl}auth/signin`,
url : 'http://xx.xx.xx.xx/',
responseType: 'json',
// withCredentials: true,
// credentials: 'same-origin',
headers: {
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Credentials': 'true',
"Access-Control-Allow-Headers": "Content-Type, Authorization",
mode: 'no-cors',
},
data: {
'email': email,
'password': password,
}
}).then((response) => {
res = response
});

Related

Axios is sending the wrong token

In React, this is working:
let token = localStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
Everything is ok. It gives success.
But in React Native (AsyncStorage), it gives wrong token error (403):
let token = AsyncStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
In console.log(token), everything seems great. I can see my token. It also works well in Postman.
According to the docs:
Returns:
Promise resolving with a string value, if entry exists for given key,
or null otherwise.
Promise can also be rejected in case of underlying storage error.
Since it returns a Promise, you should get the token using .then() or async/await:
async function doRequest() {
let token = await AsyncStorage.getItem("token");
// do request
}
I want to know whoever sees this post in the future that Axios did not send my headers in React-Native. In such a case, maybe you should try fetch.
#Rafael's answer was also great.
fetch("http://localhost/api", {
method: "post",
headers: new Headers({
"x-auth-token": `${token}`,
"Content-Type": "application/json",
}),
body: {
body
},
});

Set cookie from API response in React

I have a React app, and an API. When i POST data to APIs login url API responses me back with cookie on successful login, which I have to set, so in each next request user will send this cookie. But I can't find a method to get it from response.
I want to set sessionid, but I can't reach it within code. I tried to do
Cookies.set('sessionid', response.headers['sessionid']);
But it sets undefined. console.log(response.headers) also gives me {content-length: "31", content-type: "application/json"}. Do I do something wrong?
Sender function:
formSender() {
const url_to_send = `${this.state.api_base_url}:${this.state.api_base_port}${this.state.api_user_url}/login/`;
axios.post(url_to_send, `username=${this.state.username}&password=${this.state.password}`, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.then((response) => {
// I need to set the cookie here
this.setState({
login_success: response.status === 200,
request_sent: false
});
})
};
Try to set Access-Control-Expose-Headers in the back end or
await axios({
method: 'post',
url: YOUR_URL,
data: Data,
headers: { 'Authorization': 'TOKEN' }
});
I have the same problems and i do that for resolve in backend:
app.use(cors({
origin: true,
credentials: true
}));
and the axios request :
axios({
method: "post",
url: `http://localhost:5500/api/user/login`,
withCredentials: true,
data: {
email,
password,
},
headers: {
"Content-Type": "application/json",
}
})
.then((res) => {
console.log(res);
})
I was initially looking for a solution to setting a cookie from a response, but I realized if it's passed as a Set-Cookie header then it is set by the browser. No need to set it manually. Here is the console view
My app looks something like this:
const app = express();
app.use(cors({
origin: ['http://localhost:3000'],
methods: ['POST', 'PUT', 'GET', 'OPTIONS', 'HEAD'],
credentials: true,
}))
app.use(cookieParser())
app.get('/foo', verifyToken, (req, res) => {
// you can omit verifyToken if you want, it's for bearer auth.
if (true) {
res.cookie('XSRF-TOKEN', 'example')
res.send('Welcome')
} else {
res.sendStatus(403);
}
});
The React side:
<Button onClick={() => {
axios.get('http://localhost:8081/foo', {
params: {},
headers: {
Authorization: `Bearer 123`,
// again, omit ^ if you're not doing bearer auth
},
withCredentials: true,
}
).then((response) => {
console.log('cookie should be set')
})
}}>Express cookie</Button>
Bear in mind if you're deploying to a server both react and express should be on an https connection. Connecting http <-> https causes other issues with cookies.

Get TOKEN auth2 - POST client data - bad request

I hava a problem (404 : Bad request ) when consuming token API in my react APP .
In Post man, it work very well
const requestOptions = {
method: 'POST',
mode: "no-cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include", // include, *same-origin, omit
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
headers: {
},
body: JSON.stringify({
"client_id": "1_15dpzlnknhtwk8sgo4gwo800okogc4g00gk4k04g4g0cgc0ww0",
"client_secret": "dc86f30rr6okw8w84c8owkcko08s4k8k4c4c4k04osow8skko",
"grant_type": "password",
"username": "demoUsername",
"password": "demoPassword"
})
};
fetch('http://localhost:8000/oauth/v2/token', requestOptions)
.then(function(response) {
console.log('response');
console.log(response);
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
the result is :
this is my security.yml
It's a problem of header.the header is empty
It's work now

react js AXIOS authentication fails with network error

I am getting network error while doing axios.post request.
axios.post({
method:'POST',
url:'http://xxx.xxx.xxx.xxx:6310',
withCredentials: true,
auth: { username: 'username',
password: 'password'},
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'},
data :{"jsonrpc":"1.0", "method":"liststreams","params":[]}
}).then(function(response) {
console.log('res ------- ',response)
}).catch(function(error) {
console.log('error =',error)
})
Thanks,

headers are not being set into AXIOS post request

I am working on react-redux App. When i am making Api Post request to Rest Api(on CORS). Headers are not being set. But when i try this in postman it work perfectly.
this is the code:
I want to send TOKEN(for testing).
post: (endPoint, data) => {
return axios({
method: 'post',
url: `${apiPath}/${endPoint}`,
data: data,
headers: { "Content-Type": "application/json", 'TOKEN': 1111}
}).then((res) =>{
return res;
})
}

Resources