AXIOS request method changes to 'OPTIONS' instead of 'GET' - reactjs

I am trying to call and API with react app(TSX) using Axios(this the first time I am using Axios) every time I run the app the method changes to 'OPTIONS' and the request becomes invalid. Help will be appreciated. Sharing my code sorry I am hiding the Auth Token for security reasons.
Code
import React, { useState, useEffect } from 'react';
import axios from 'axios';
interface Brands {
BrandId: number;
Name: string;
}
const AUTH_TOKEN = Something hiden for security;
var baseUrl = axios.defaults.baseURL = 'https://fppdirectapi-prod.fuelpricesqld.com.au/Subscriber/GetCountryBrands?countryId=21';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.get['Content-Type'] = 'application/json';
axios.defaults.method = 'get';
const FetchFuelType = () => {
const [brands, setPosts] = useState<Brands[]>([]);
useEffect(() => {
axios.get(baseUrl)
.then(res => {
console.log(res)
setPosts(res.data)
})
.catch(err => {
console.log(err)
})
}, [])
return (
<div>
<ul>
{brands.map(Brand => (<li key={Brand.BrandId}>{Brand.Name}</li>))}
</ul>
</div>
);
};
export default FetchFuelType;
Attached image of response

OPTIONS request is part of the so-called preflight request which is needed to figure out the CORS headers to know what needs/is allowed to be sent to the server with the actual GET request. Thats why you normally see two requests in your network tab (depending on your setting)
In your example it seems you have not configured anything CORS related on your server (thus the 405) or specifically have forbidden anything other than GET/POST requests. Or potentially the site has forbidden others to access its data

Usually, options request is sent before get automatically by axios, to get some preliminary data before firing get call. Check this https://github.com/axios/axios/issues/475.

The OPTIONS request is an inherent request generated by browser.
Browser uses the OPTIONS call to find out what methods are allowed by the server.
The API server meant for supporting requests from browser must allow OPTIONS in addition to the actual method (GET / POST / etc).
If the server does not support OPTIONS, then it may not support browser.
A server that does not support OPTIONS can only support non-browser clients
(Examples: REST client in Java / nodejs)
How to solve the problem?
The problem of '405 - OPTIONS method not allowed' can be solved in one of these 2 ways:
Update the server to support OPTIONS method (Recommended for server that is supposed to support browsers)
Develop an 'Intermediary REST client' which will request data from the server, on behalf of the browser
Browser <--> REST client (supports OPTIONS, POST) <--> Actual web service (does not support OPTIONS)

Related

csurf with React: Invalid token after changing user

I've had csrf protection with the csurf module working for a while now on my React SPA. I am also using passport for authentication. I do not do any server-side rendering, so the server sends a csrf token in the response body to the client when it hits the /users/current endpoint, which is protected with csrfProtection, something like this:
import csrf from 'csurf';
const csrfProtection = csrf();
router.get("users/current", csrfProtection, async function(req, res)
{
.....
res.write(JSON.stringify({ ..., csrfToken: req.csrfToken() }));
res.end();
}
On the client side I then add the token to all subsequent request headers, a bit like this:
axiosInstance.get("/users/current")
.then(resJson =>
{
axiosInstance.interceptors.request.use(config =>
{
config.headers["x-csrf-token"] = resJson.data.csrfToken;
return config;
});
}
My first question is how the first request even manages to pass the csrfProtection without a token in its header. Yet since the token can only be accessed on the server to send to the client if the route is csrf protected, I don't see a way around this, and it does work somehow.
However, recently I have been getting "ForbiddenError: invalid csrf token" when a user logs in or deletes their account. This has only started happening after I upgraded all my node packages to the latest versions. First the client makes a request to /users/login to submit the username & password, and then makes a request to /users/current to get the new csrf token:
axiosInstance.post("/users/login", {
"username": login.username,
"password": login.password
})
.then(async resJson =>
{
// *code to update user details in redux store*
// ......
axiosInstance.interceptors.request.use(config =>
{
config.headers["x-csrf-token"] = undefined;
return config;
});
return resJson;
})
.then(async resJson =>
{
const { csrfToken } = await axiosInstance.get("/users/current")
.then(resJson => resJson.data);
axiosInstance.interceptors.request.use(config =>
{
config.headers["x-csrf-token"] = csrfToken;
return config;
});
return resJson.data;
}
I suspect it's something to do with subsequent requests coming from a different userId (which I obtain from req.user[0].userId), with which csurf will not accept the previously issued token. But I have no idea how to issue the new token csurf does expect, to the client. And it still doesn't explain why what I had before has suddenly stopped working since none of my logic has changed. This isn't the kind of error I'd typically expect after package updates.
Here someone mentions you can just set any header on the client and have the server check for that. atm I am adding the csrf token to all the client's request headers and using the csurf module's request handler function to check it, but there is nothing stopping me from writing my own. If this is true, the value of the header doesn't even matter, just that it exists. I am holding off on this option though because I feel there is something basic I'm not understanding about my current setup, which once rectified will mean this can be easily fixed.
Would appreciate any help or explanation! Thanks 🤍

What's the best way to store a HTTP response in Ionic React?

I'm developing an app with Ionic React, which performs some HTTP requests to an API. The problem is I need to store the response of the request in a local storage so that it is accessible everywhere. The way I'm currently doing it uses #ionic/storage:
let body = {
username: username,
password: password
};
sendRequest('POST', '/login', "userValid", body);
let response = await get("userValid");
if (response.success) {
window.location.href = "/main_tabs";
} else if (!response.success) {
alert("Incorrect password");
}
import { set } from './storage';
// Handles all API requests
export function sendRequest(type: 'GET' | 'POST', route: string, storageKey: string, body?: any) {
let request = new XMLHttpRequest();
let payload = JSON.stringify(body);
let url = `http://localhost:8001${route}`;
request.open(type, url);
request.send(payload);
request.onreadystatechange = () => {
if (request.readyState === 4 && storageKey) {
set(storageKey, request.response);
}
}
}
The problem is that when I get the userValid key the response hasn't come back yet, so even awaiting will return undefined. Because of this I have to send another identical request each time in order for Ionic to read the correct value, which is actually the response from the first request. Is there a correct way of doing this other than just setting timeouts everytime I perform a request?
You are checking for the results of storage before it was set. This is because your sendRequest method is calling an asynchronous XMLHttpRequest request, and you are checking storage before the sendRequest method is complete. This can be fixed by making sendRequest async and restructuring your code a bit.
I would suggest you instead look for examples of ionic react using hooks or an API library - like fetch or Axios. This will make your life much easier, and you should find lots of examples and documentation. Check out some references below to get started:
Example from the Ionic Blog using Hooks
Example using Fetch using React
Related Stack Overflow leveraging Axios

It was set headers and axios but Why happen cros error?

Premise / What you want to achieve
React x Redux (port: 3000)
Go (port: 8080)
I am making a SPA.
I run into a CROS error when hitting the Go API.
I've encountered this problem many times, and every time I think it's solved, I hit a new API.
I should have made the basic settings, but I'm in trouble because I don't know what caused it.
We would appreciate it if you could help us.
Problem / Error message
Access to XMLHttpRequest at'http://localhost:8080/login' from origin'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No'Access-Control -Allow-Origin'header is present on the requested resource.
I encountered this when I hit the login API (post).
However, when I encountered this problem several times, I set cros on the header of api and axios side, and
Another get API avoided the error.
Also, when you hit api with postman, it becomes header
We have also confirmed that the header set in Go such as Allow-Origin is given without any problem.
Applicable source code
Header settings in Go
w.Header (). Set ("Content-Type", "application /json")
w.Header (). Set ("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header (). Set ("Access-Control-Allow-Credentials", "true")
react axios settings
axios.defaults.baseURL ='http://localhost:8080';
axios.defaults.headers.post ['Content-Type'] ='application/json';
Posting code with an error
export const signIn = (email, password) => {
return async (dispatch) => {
try {
const response = await axios.post ('/login', {
email: email,
password: password,
});
const data = response.data;
dispatch (
signInAction ({
isSignedIn: true,
})
);
} catch (error) {
console.log (error);
}
};
};
Code hitting a successful getapi
useEffect (() => {
async function fetchTickers () {
try {
const response = await axios.get (`/ticker?Symbol=^skew`);
const data = response.data;
setChartAry ([... chartAry, [... data.daily]]);
} catch (error) {
console.log (error);
setChartAry ([]);
}
}
fetchTickers ();
}, []);
What I tried
I tried all the solutions that hit with stackoverflow etc. Also, considering the possibility of a problem with the browser itself, we also cleared the cache.
Is it the difference between axios by get and post? And how should I debug it?
I had this problem some time ago but I used Express for the backend, who knows this can solve your problem too.
try adding this to the axios settings axios.defaults.withCredentials = true;
You also need to allow the OPTIONS method for preflight requests
this article might help you solve the CORS problem on the backend: https://flaviocopes.com/golang-enable-cors/
The method was validated in gorilla / mux.
- r.HandleFunc("/login", app.loginHandler).Methods("POST")
+ r.HandleFunc("/login", app.loginHandler).Methods("POST", "OPTIONS")
We also had to deal with preflight.
if r.Method == "OPTIONS" {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusOK)
return
}

React/Axios API Get Request Issues (CORS & Internal Server Error 500)

I am attempting to complete an axios GET request to an API and I'm running into an Internal Server Error - 500 and I'm curious if this is simply my code and/or my attempt at making this call or something else. Even though the CORS issue seems to be behind me, I'll start from the beginning just in case its related to my current issue.
My initial attempt at the request gave me the following CORS error:
...from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight
request doesn't pass access control check: It does not have HTTP ok status.
After doing a lot of research on this, I found that I could append https://cors-anywhere.herokuapp.com to my target API URL and get around this issue. So far, so good but now I am getting the following locally in my browser: net::ERR_NAME_NOT_RESOLVED
So I decided to jump over to Postman and input the given headers to access this API to see if I could find more information and I'm getting the following on Postman:
{
"timestamp": "2020-11-13T01:04:47.288+0000",
"message": "General error occurred please contact support for more details",
"error": "Internal Server Error",
"status": 500
}
Now, within the documentation of this API, it states that a 500 is a server error on their part but I'm not confident in that as I think it may just be my own doing here. So I basically have two questions...
Should the developer of the API do/change anything to avoid the CORS issue or is that a common thing to run into?
Is the 500 error response on me or them?
Below is my axios request in my App.js file of my React application. Please let me know if any other code or info is needed. Thanks so much in advance for any help!
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class App extends Component {
state = {
events: []
}
constructor() {
super();
const proxyURL = 'https://cors-anywhere.herokuapp.com'
const URL = 'https://api.example.com/api/'
const proxiedURL = proxyURL + URL
axios.get(proxiedURL, {
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + process.env.REACT_APP_AUTH_API_KEY
}
})
.then((res) => {
console.log(res.data)
})
.catch((error) => {
console.log(error)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<h1>Data</h1>
</header>
</div>
);
}
}
export default App;
According to the documentation for cors-anywhere:
This API enables cross-origin requests to anywhere.
Usage:
/ Shows help /iscorsneeded This is the only resource
on this host which is served without CORS headers. /
Create a request to , and includes CORS headers in the response.
Your code is missing a trailing slash after https://cors-anywhere.herokuapp.com to work, i.e.: https://cors-anywhere.herokuapp.com/.
To answer your two other questions:
CORS issues are very common and it is up to the developer of the API to set from which domain the API can be called. More on MSDN
The 500 response means this in an internal server error, so on the server-side. Though it can be because of many reasons, like querying the wrong URL, passing unexpected data... Ideally all these should be covered and different errors would be returned every time but this is rarely the case. :)

Nextjs + expressjs + Azure Web App : two factor authentication with express ('fs' can't be used on client side)

Stack : next.js/express.js/typescript/nodemon
I have a dependency on azure devops api which seems to be using 'fs' under the hood. So I can't use this library in any of the pages (including in getInitialProps).
I created a custom route (call it "get_data") in express server which provides me with the data. I call this route in getInitialProps of the page that will render the data (call it data.tsx) .
The whole app is behind two factor authentication in azure web apps. when get_data call is made in getInitialProps, I get a 401. Note that the origin is the same for serving the page and the get_data api.
Is there a way to pass current auth context when I make the get_data api call ?
In the express api, the method currently looks like this :
server.get('/get_data', (_req, res) => {
let ado = new azure_devops() // this uses the azure-devop-api package
ado.get_data().then((data) => {
res.setHeader('Content-Type', 'application/json');
res.json(data) // return data as json
})
});
Is there a way to merge the two (page and data serving) like the following (so I don't have to make extra api call with auth setup) ?
server.get('/data', (req, res) => { //note the change in route that serves the page data.tsx
const actualPage = '/data';
let ado = new azure_devops() // this uses the azure-devop-api package
ado.get_data().then((data) => {
res.setHeader('Content-Type', 'application/json');
res.write(data) // BUT this is where method returns instead i want to just add to the response body
app.render(req, res, actualPage); // THIS is not executed (so the page doesn't get rendered)
})
});
Appreciate any pointers.
Got the answer from this question.
Still making the API request from getInitialProps. I was missing adding cookie from the context.
const res = await fetch('http://' + context.req.headers.host + '/get_data', {
headers: {
cookie: context.req.headers.cookie, // WAS MISSING THIS
}
});

Resources