Axios call api with GET become OPTIONS - javascript

I use axios for calling API (in front-end).
I use the method "GET" :
import axios from 'axios';
import querystring from 'querystring';
var url = "mydomain.local",
token = "blablabla...blabla";
var configs = {
headers: {
'Authorization': 'Bearer ' + token,
'Agency': 'demo0'
}
};
var testapi = axios.create({
baseURL: 'http://api.' + url
});
testapi.get( '/relativeUrl', configs
).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
I got a 405 Method Not Allowed. The method is "OPTIONS" but I use the method ".get()".
405 Method Not Allowed. Method OPTIONS
I test call api with postman and I get 200 OK :
postman 200 OK screenshot
Anyone has an idea ?

Like #Shilly says, OPTIONS method is pre-flight on modern browsers when Preflighted requests conditions (MDN) :
In the response header I had Allow:"GET, HEAD, POST, PUT, DELETE".
So OPTIONS method is not available and need to configure it on in the server (Apache).
I do the change on apache (/etc/apache2/sites-available/000-default.conf) :
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
In Request headers I have :
Origin: "null" is a problem. The cause is :
file:// URLs produce a null Origin which can't be authorized via
echo-back. Don't trying to perform a CORS request from a file:// URL (see this post for more details)
After put my javascript file on a apache server, the Origin was not null but I need to add NelmioCorsBundle to my Symfony project to allow preflight

So the way to solve this npm install qs.
Then:
import qs from 'qs'
function send(params) {
return axios.post('/api/create/', qs.stringify(params))
}

Related

Flask API with CORS error in delete method

I have developed a rest api in Flask. All my api endpoints work fine when I test them with postman.
Now, I am developing an application with Javascript that consumes the resources of my api.
I'm having trouble consuming an endpoint that works with the delete method. Endpoints with get and post work fine, but not the delete method. I get the next CORS error:
Access to fetch at 'http://localhost:5000/contacto' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
This is my Javascript code:
let data ={id: id};
let url = "http://localhost:5000/contacto";
fetch(url, {
credentials: 'include',
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
alert(res.result);
});
On the server side, I use flask_cors. I configure the app with this code:
from flask import Flask, jsonify, request
from flask_cors import CORS
import controllers.userController as userController
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
#CORS(app)
#CORS(app, resources={r"/*": {"origins": "*"}}, send_wildcard=True)
CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})
The path of my service with delete method is this:
#app.route('/contacto', methods = ['DELETE'])
def deleteContacto():
parametros = request.args
id = parametros['id']
result = contactController.eliminar_contacto(id)
response = None
if result == True:
response = jsonify({'result':'Contacto eliminado con éxito'})
else:
response = jsonify({'result':'Error al eliminar el contacto'})
response.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
return response
I need some help. I have searched and tried many possible solutions but they do not work for me. I'm a bit desperate.
Thanks in advance and regards.
I do this a bit different, but make sure you have this option set to allow delete and options methods:
'Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'
I add them manually to the response object in flask
resp.headers.add('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS')
CORS should be setting this as a default, but maybe something is misconfigured?
see the docs:
https://flask-cors.readthedocs.io/en/latest/configuration.html

How to read custom header in CORS middleware

I have created CORS middleware using CORS package. This middleware will be called before each call. Here is my implementation.
const corsMiddleware = async (req, callback) => {
const { userid } = req.headers|| req.cookies {};
let whiteList = await getWhiteListDomains(userid)
return callback(null, {
origin: whiteList,
credentials: true,
allowedHeaders: ["userid", "authorization", "content-type"]
});
};
And added this middleware before route initialization as
app.use(cors(corsMiddleware));
app.options("*", cors(corsMiddleware));
app.get("/user", (req, res, next)=>{
// code
})
From Browser I am trying to call the API as
axios({ method: "get", url: "http://localhost:3000/user", headers: {userId:"1234"} });
While debugging on the server I see
access-control-request-headers:"userid"
in the headers of the request object.
I am not able to read the custom header. This might be happening because I am trying to read the custom header before CORS initialization. But still, I want to read that custom header.
You have mainly two problems in your code.
First one, and easier to solve is that you are missing access-control-allow-origin in the option that sets the Access-Control-Allow-Headers:
return callback(null, {
origin: whiteList,
credentials: true,
allowedHeaders: [
"access-control-allow-origin",
"authorization",
"content-type",
"userid"
]
});
The second one is the most important because it is related to how CORS works.
This problem you are having is that CORS is already rejecting the petition in the pre-flight OPTIONS request. It never allows the browser to execute the GET request.
You say that you want to read the custom header userId in the pre-flight OPTIONS request but you can't. The reason is because the pre-flight OPTIONS request is created by the browser automatically and it won't use the custom headers you are setting up in the Axios call. It will only send these headers for the CORS:
Origin // URL that makes the request
Access-Control-Request-Method // Method of the request is going to be executed
Access-Control-Request-Headers // Headers allowed in the request to be executed
Because your custom header is not being sent so in the pre-flight OPTIONS when you try to access the value of userId, you get an undefined value:
const { userid } = req.headers|| req.cookies;
console.log(userid); // undefined
And because you are using that value that is not matching in your async function getWhiteListDomains probably getting another undefined, the value set up in the origin option of the CORS middleware is undefined that provokes the CORS middleware rejects the pre-flight OPTIONS request.
let whiteList = await getWhiteListDomains(userid); // userid === undefined
console.log(whitelist); // undefined
return callback(null, {
origin: whiteList, // undefined
credentials: true,
allowedHeaders: ["userid", "authorization", "content-type"]
});
I am not totally sure which is your goal trying to use your custom header as CORS check, but my advise would be when dealing with customised CORS configuration to only check the Origin header because that's its purpose: to limit and control which URLs can access to your server and resources.
If you are interested in creating any kind of authorisation or limited by user implementation in the requests received by your server, I suggest you to use a different custom middleware and not involve CORS at all like you are trying now.
you must parse your request
try this
npm i body-parser
and
const bodyParser = require('body-parser');
app.use(bodyParser.json())

Ionic can't get open cors

I am trying to get API data from live server in ionic android app but it returns this error:
Access to XMLHttpRequest at 'https://example.com/api/categories/' from origin 'http://192.168.43.71:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Server settings
Now I am using Laravel for live server which is giving the API here is how I set CORS in my laravel application:
/bootstrap/app.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
header('Access-Control-Allow-Headers: *');
// rest of the file
due to my setup above I'm getting this result on CORS tester
Ionic settings
So I've been reading how to solve this issue and came cross lots of similar solutions and this is what I add to my ionic.config.json file
"proxies": [
{
"path": "/api/*",
"proxyUrl": "https://example.com/api/"
}
]
Get request (ionic services)
Here is how I request my get method
apiUrl = 'https://example.com/api/categories/';
constructor(private http: HttpClient) { }
getCategories(): Observable<any> {
return this.http.get(`${this.apiUrl}`).pipe(
map(categories => categories)
);
}
Any idea what else should I do to fix this issue?
SOLVED
Thanks to Stephen Romero for pointing the important part of this solution,
based on stephen answer I added this code to my function:
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
and used it in my get request like:
return this.http.get(`${this.apiUrl}`, httpOptions).pipe(
Now the for header permissions I used (installed) this package for on my laravel app and made config file set as code below:
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['GET', 'OPTIONS'],
'exposedHeaders' => [],
'maxAge' => 0,
];
FOR those who doesn't use Laravel
Set your headers like this:
if($request_method = 'GET'){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Authorization, Expires, Pragma, DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range');
header("Access-Control-Expose-Headers: *");
}
The most important part of this headers is Access-Control-Allow-Headers part, if you simply use * it won't work! you need to set headers name.
Hope it helps.
Update
Forgot to mention in order to avoid error 301 you need to remove / from end of your api url.
// my api (before)
https://example.com/api/categories/
//changed to
https://example.com/api/categories
I solved my issue using these Headers for my API:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods:GET,POST");
header("Access-Control-Allow-Headers: Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
And Angular Http:
//GET data details
getData(authToken){
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json',
'Authorization': authToken
})
};
//console.log(authToken);
return this.http.get(this.apiGetUrl, httpOptions).retry(3);
}
Like the previous answer, an Options request automatically gets sent with the GET or POST. If you have apache servers, you can echo$headers = apache_request_headers(); to see what is all coming through. Comparison for $_SERVER and Apache here.
In my case, I run if statements:
if(isset($headers["Authorization"]) && isset($headers["Content-Type"])){
//handle get request
}
else{
//handle options request
echo " False,Re-routing Options Request";
}
I would test your HTTP call in the browser and look at dev tools to confirm the requests being sent. I hope this helps!
Perhaps at some point a preflight OPTIONS request is done by the client and since it isn't a listed method in your Access-Control-Allow-Methods it ends up in a CORS issue.
You should try to make a request to your server endpoint with OPTIONS method to check if this is the case, you can use POSTMAN to make this test.
Then try to add the OPTIONS method to the Access-Control-Allow-Methods and check the difference.

Access-Control-Allow-Origin issue in ktor cors header

I am building a simple REST API using ktor and used cors but when i send a simple get request with no headers data the server works fine but if i want the client to have say key:1 the server doesn`t respond me correctly, it says the problem is
Failed to load http://127.0.0.1:8080/test: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.
so here is my ktor code
install(ContentNegotiation) {
gson {
}
}
install(ForwardedHeaderSupport)
install(DefaultHeaders)
install(CORS)
{
method(HttpMethod.Options)
method(HttpMethod.Get)
method(HttpMethod.Post)
method(HttpMethod.Put)
method(HttpMethod.Delete)
method(HttpMethod.Patch)
header(HttpHeaders.AccessControlAllowHeaders)
header(HttpHeaders.ContentType)
header(HttpHeaders.AccessControlAllowOrigin)
allowCredentials = true
anyHost()
maxAge = Duration.ofDays(1)
}
...
get("test"){
val a = call.request.headers["key"]
println(a)
call.respond(Product(name = a))
}
and my javascript code looks like this....
fetch('http://shop-ix.uz:8080/test', {
headers: {
"key": "1"
})
.then(response => response.json())
.then(json => {
console.log(json);
})
please help me
You need to whitelist your headers like this:
install(CORS) {
header("key")
}
This needs to be done with every custom HTTP header you intend to use.
Make sure all the headers and required methods should be allowed during Ktor CORS installation. I was facing the same issue, then I realized that I didn't add allowHeader(HttpHeaders.AccessControlAllowOrigin)
Although in the request header it was present. Because of that I am getting forbidden error (403)!
My Request Header!
Axios({
method: 'GET',
url: 'http://127.0.0.1:8080/connect',
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
params: {
...
}
})
Allowing CORS
install(CORS) {
allowMethod(HttpMethod.Options)
allowMethod(HttpMethod.Post)
allowMethod(HttpMethod.Get)
allowHeader(HttpHeaders.AccessControlAllowOrigin)
allowHeader(HttpHeaders.ContentType)
anyHost()
}
Check that what your request header wants is allowed on the server during CORS.
install(CORS) {
exposeHeader("key")
}
difference between header and exposeHeader - first allow to make call with this header, but second allow to use it on client side

Fetch Request Not Working

I am trying to add a custom header, X-Query-Key, to a HTTP request using Fetch API or request but when I add this to the header of the request it appears to fail at setting the headers and the Request Method is set to OPTIONS for some reason.
When I remove the header it goes back to being GET as it should do.
Sample code looks like below:
const options = {
url: url,
headers: {
'Accept': 'application/json',
'X-Query-Key': '123456' //Adding this breaks the request
}
};
return request(options, (err, res, body) => {
console.log(body);
});
Try this:
const headers = new Headers({
"Accept": "application/json",
"X-Query-Key": "123456",
});
const options = {
url: url,
headers: headers
};
return request(options, (err, res, body) => {
console.log(body);
});
If that does not solve the issue, it may be related to CORS.
Custom headers on cross-origin requests must be supported by the
server from which the resource is requested. The server in this
example would need to be configured to accept the X-Custom-Header
header in order for the fetch to succeed. When a custom header is set,
the browser performs a preflight check. This means that the browser
first sends an OPTIONS request to the server to determine what HTTP
methods and headers are allowed by the server. If the server is
configured to accept the method and headers of the original request,
then it is sent. Otherwise, an error is thrown.
So you will have 2 requests if use custom headers, first one with method OPTIONS to check if server allows custom headers and after that if the server response is 200 OK and allows your originary request the second one will be send
Working with the Fetch API

Categories

Resources