CORS the easyway - angularjs

I'm trying to 'put' data to my Laravel 5 server running on localhost from a webpage thats is also served localhost, but from other server software (nodejs). But im getting this error:
XMLHttpRequest cannot load http://localhost:8888/data/. Method PUT is not allowed by Access-Control-Allow-Methods.
The code that creates the put request is angularjs and looks like this:
return $http.put("http://localhost:8888/data/", { obj1: a, obj2: b });
What is the simplest way to get around CORS? Security is no issue.
Using the postman plug-in in chrome I'm able to send the put request.

This is my laravel setup for cors.
I've created an http.php config file with this settings:
return [
'cors' => [
'origin' => '*',
'methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE',
'headers' => 'X-Requested-With, Content-Type, Authentication-Token',
],
];
Run this code somewhere on application startup:
if ( ! App::runningInConsole()) {
header('Access-Control-Allow-Origin: ' . Config::get('http.cors.origin'));
header('Access-Control-Allow-Credentials: true'); // to be honest i've never used this option, but it looks like you'll need it
// handle preflight requests
App::before(function() {
if (Request::getMethod() === 'OPTIONS') {
return new Response('', 200, [
'Access-Control-Allow-Methods' => Config::get('http.cors.methods'),
'Access-Control-Allow-Headers' => Config::get('http.cors.headers'),
]);
}
});
}

Postman doesn't use CORS.
To enable CORS (in the client side) add : { withCredentials: true } in your put options :
return $http.put("http://localhost:8888/data/", { obj1: a, obj2: b }, { withCredentials: true });
Note: Depending on your server application, you may enable them in the server side too.

It doesn't seem to be an Angular problem. You should try enabling CORS on the PHP with:
// Enable CORS
// In production, replace * with http://yourdomain.com
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');

Related

CORS error when calling a Firebase function

I am using Google Cloud Functions and I am getting an error related to CORS. I have made a simple function but it's not working because I keep getting the same error over and over again. I have tried almost everything but nothing is working.
Here is the code I am using:
const cors = require('cors')({origin: true});
exports.sample = functions.https.onRequest((req, res) => {
cors(req, res, () => {
res.send('Passed.');
});
});
I have used this and other things too people recommended. I tried adding headers too - but nothing worked.
You should add the header Access-Control-Allow-Origin: * in the response from the Google Cloud Function (GCF).
def cloud_function(request):
response = 'what you expect to return from the GCF'
http_code = 200
headers = {
'Access-Control-Allow-Origin': '*'
}
return response, http_code, headers
Notice the header added on the return from the Cloud Function. If you are forced to return more CORS headers you can add them to the headers variable (or if you want to return other headers for any other reason). For example:
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Authorization',
'Access-Control-Max-Age': '3600',
'Access-Control-Allow-Credentials': 'true'
}
https://cors-anywhere.herokuapp.com/YOUR-URL.
You can use this proxy to bypass the cors issue if it's not for any production use.
OR
You can use Access-Control-Allow-Origin: * in header while hitting the link.

I can't perform a request from ReactJS. The header can not be written correctly

axios.get('http://localhost:8080/omp/patients', { headers: {authorization: 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
In network I have the field: "Access-Control-Request-Headers: authorization" but no field "authorization: token"
You will need to set the Authorization header correctly, as in the comment above.
For your reply about CORS Policy:
You will need to learn about CORS, but essentially Chrome and other browsers halt network requests if they do not have proper CORS headers set upon response. A preflight is an initial request that is sent to the same URL to learn whether the URL will support CORS, before sending the actual request. It looks like the server doesn't understand CORS preflights or isn't configured properly.
You have a couple options:
If you have access to the server configuration or code (such as a Laravel or NodeJS server), install a CORS plugin.
If you are the only user using this, you can install CORS browser extensions for Chrome or Firefox or whatever.
Change your code to this:
axios.get('http://localhost:8080/omp/patients', { headers: { "Authorization": 'Bearer ' + token}})
.then( response => {
this.state = response.data;
}
).catch(ex=> {
alert("You are not registered");
//console.log(e)
});
Also in you app.js/index.js where ever you are running your server import/require cors module and do like this:
let cors = require('cors');
app.use(cors());
Hope this helps!

CORS error when calling post api directly from client

I have a post function that I have tested and is working perfectly. When I call it from my front end, I get the following error:
Access to XMLHttpRequest at 'https://sdigg5u4xb.execute-api.eu-west-1.amazonaws.com/prod/sites' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried disabling CORS and using different cognito identity pools to allow different permissions, but I still get the same error. When testing it in AWS, it is successful with no errors.
Here is where I am calling the API:
import { API } from "aws-amplify";
export default (async function submitSite(values) {
console.log(values);
return API.post("sites", "/sites", {
body: values
})
});
Here is where I am defining the function in my serverless.yml file:
createSite:
handler: CreateSite.main
events:
- http:
path: sites
method: post
cors: true
authorizer: aws_iam
I'd recommend you to check these.
Make sure you enable CORS in your API gateway as described here
Make sure your server less app have CORS enabled here.
Don't forget adding Access-Control-Allow-Origin response header to your function.
module.exports.hello = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);

Axios having CORS issue

I added proxy in package.json and it worked great, but after npm run build the CORS issue has resurfaced again, does anyone know how to deal with CORS issue after npm run build in React.
I have tried to add headers in axios request using various methods. However, I failed to add 'Access-Control-Allow-Origin':'*' in axios request. My code is as follwing:
package.json
"proxy": {
"*":{ "target" : "http://myurl"}
}
GetData.js
axios.defaults.baseURL = 'http://myurl';
axios.defaults.headers.post['Content-Type'] ='application/json;charset=utf-8';
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.get(serviceUrl, onSuccess, onFailure)
.then(resp => {
let result = resp.data;
onSuccess(result);
})
.catch(error => {
if(onFailure) {
return onFailure(error);
}
})
}
Note: It has enabled from server side, it is still not working.Currently, I can't change code from server side, My work is limited to client side only.
your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
Just noting my solution for someone who might get here from googling. I resolved my CORS issue (when calling an external api from my UI in the browser) by setting withCredentials to false in my axios call:
axios({
method: 'get',
url: `https://api.someurl.com/subject/v2/resource/somevalue`,
withCredentials: false,
params: {
access_token: SECRET_TOKEN,
},
});
In this case, the external api's endpoint's security is based on the access_token.
May be helpful to someone:
I'm sending data from a react application to a golang server.
Once I change this, w.Header().Set("Access-Control-Allow-Origin", "*"), the error was fixed.
React form submit function:
async handleSubmit(e) {
e.preventDefault();
const headers = {
'Content-Type': 'text/plain'
};
await axios.post(
'http://localhost:3001/login',
{
user_name: this.state.user_name,
password: this.state.password,
},
{headers}
).then(response => {
console.log("Success ========>", response);
})
.catch(error => {
console.log("Error ========>", error);
}
)
}
Go server got Router,
func main() {
router := mux.NewRouter()
router.HandleFunc("/login", Login.Login).Methods("POST")
log.Fatal(http.ListenAndServe(":3001", router))
}
Login.go,
func Login(w http.ResponseWriter, r *http.Request) {
var user = Models.User{}
data, err := ioutil.ReadAll(r.Body)
if err == nil {
err := json.Unmarshal(data, &user)
if err == nil {
user = Postgres.GetUser(user.UserName, user.Password)
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(user)
}
}
}
I have encountered with same issue. When I changed content type it has solved. I'm not sure
this solution will help you but maybe it is. If you don't mind about content-type, it worked for me.
axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources. So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.
Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.
const cors = require("cors");
app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));
app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));
I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.
I had got the same CORS error while working on a Vue.js project. You can resolve this either by building a proxy server or another way would be to disable the security settings of your browser (eg, CHROME) for accessing cross origin apis (this is temporary solution & not the best way to solve the issue). Both these solutions had worked for me. The later solution does not require any mock server or a proxy server to be build. Both these solutions can be resolved at the front end.
You can disable the chrome security settings for accessing apis out of the origin by typing the below command on the terminal:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir="/tmp/chrome_dev_session" --disable-web-security
After running the above command on your terminal, a new chrome window with security settings disabled will open up. Now, run your program (npm run serve / npm run dev) again and this time you will not get any CORS error and would be able to GET request using axios.
Hope this helps!
This work out for me :
in javascript :
Axios({
method: 'post',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order
}).then(function (response) {
console.log(response.data);
});
and in the backend (.net core) :
in startup:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
and in controller before action
[EnableCors("AllowOrigin")]
CORS issue is something you will only encounter on a Broswer. It occurs beacuse the server does not allow request from others servers
i.e If I am sending request from http://localhost:3000 to any api(http://example.com/users) to get the user data from here.
If the server does not recognize your local host
#CrossOrigin(Origin = "*") // this will allow any request from any server you will not face CORS issue if you us this annotation
Now what if you are sending a request using axios in react to another sever which is not in your control the way to overcome that issue is by using http-proxy-middleware
npm i http-proxy-middleware // install this dependency
axios.{
method: 'post',
url: '/endpoint',
headers: {
'Content-Type': 'application/json',
},
proxy: createProxyMiddleware({
target: 'https://www.api.com',
changeOrigin: true}),
data: data
};
Now in this way a proxy request to www.api.com/endpoint will be sent and thus you will not recieve a cors issue
also add this in your package.json
"proxy": "https://www.api.com"
I come across this thread when having the same problem using Axios. What was not mentioned in the responses is that using fetch with no-cors mode can solve your issue.
Why ?
Apparently, Axios uses a XMLHttpRequest under the hood, not Request
and Axios fails because CORS is still being enforced and no-cors mode
is not supported.
Check this thread for more information
Please try this .. it worked for me
axios.get(`http://localhost:4000/api`,{ crossdomain: true }).then((result)=>{
console.log("result",result);
}).catch((error)=>{
console.log("Error",error);
});
Just simply add this to your headers
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
No need to use Access-Control-Allow-Origin : *
CORS issue can be simply resolved by following this:
Create a new shortcut of Google Chrome(update browser installation path accordingly) with following value:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="D:\chrome\temp"

CORS Preflight error with Apache, Laravel and AngularJS

I have implemented a backend with an Apache server with AMI from AWS and Laravel. For authentication I use the JWT Auth plugin.
My frontend is build with AngularJS. Before using the authentication everything worked fine. When I try to authenticate the user with an authorization header I get a CORS Preflight error. I use the following call from my AngularJS application:
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.common.Accept = "text/plain";
$http({
url: 'http://MYURL',
method: "GET",
headers: {
'Access-Control-Allow-Headers': 'Authorization, Content-Type, Accept',
'Content-Type' : 'text/plain',
'Authorization': 'Bearer '+token,
}
})
In my Laravel backend I used the following configuration:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Authorization, Content-Type");
This is the response from the OPTIONS call:
This is the error I get in Google Chrome:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
Any ideas on this issue? Do I have to configure this within Angular, Laravel or my httpd.conf?
EDIT:
I added it as a global Middleware and in the app.php as service provider.
The configuration looks like this:
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Authorization, Content-Type'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],
];
But I have no idea if it works correctly.
Have you considered using a plugin for managing CORS setup like this one?
It appears that the list of headers you allow on the server side (Authorization, Content-Type) is not the same as the list of headers being sent by the request (Authorization, Content-Type, Accept). It could be that the front end is asking for permissions that you aren't allowing on the back end.

Resources