handleLoginClick(event) {
var apiBaseUrl = "http://localhost:8000/api-token-auth/";
var self = this;
var payload={
"email": "myusername",//this.state.username,
"password": "mypassword"//this.state.password
};
axios.post(apiBaseUrl, payload)
.then(function (response) {
alert('success')
})
.catch(function (error) {
alert('NO') . // <----- always reaches here.
console.log(error);
});
}
For some reason, this code always fails and alert 'NO'. the endpoint I'm trying is valid, and accessible with those parameters from curl. Any ideas what's wrong?
I do have:
import axios from 'axios';
Console output:
XMLHttpRequest cannot load http://localhost:8000/api-token-auth/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Your requests are not readable by the JavaScript due to Same-origin policy. In order to allow cross-domain requests, you must enable Cross-Origin Resource Sharing (CORS) headers server-side.
For development purposes, you may use a proxy (own, or a simple service like crossorigin.me) or the Allow-Control-Allow-Origin: * Chrome Extension.
To allow calls from any domain you must serve the following header (* - means any, however, you can list domains here):
Access-Control-Allow-Origin: *
To enable CORS in Django app please see django-cors-headers or django-cors-middleware.
Related
I have written the following code in my react js file, in the place of URL there is my AWS link.
const { empid, name, author } = body;
const onInputChange = e => {
setUser({ ...body, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
axios.post(url, body);
history.push("/");
console.log(body);
};
This is my error I have already added Moesif origin crops extension to my browser :
Access to XMLHttpRequest at 'url' 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.
Check if the API has CORS disabled
Check if there a trailing / at the end of the api that you are calling. If there a trailing / then remove it. Ex: www.example.com/api/get_lists/ should be www.example.com/api/get_lists
You need to enable cors on your Api Gateway resource.
Also if you are using lambda proxy you need to return cors headers from your lambda response as well.
return {
statusCode: 200,
body: '<response as string>',
headers: {
'Access-Control-Allow-Origin': 'your allowed domains',
... // Other cors headers
}
}
Looks like that the CORS option is not enabled on your API Gateway Resource.
1 - Go to your API Gateway Resource and enable CORS.
2 - Re deploy your API Gateway for the changes to take effect.
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);
I'm trying to fetch my data from a heroku app into Redux, but I think I'm running into a CORS issue. I've been playing with "headers" for a while and still can't figure it out.
This is the exact error:
"Failed to load https://name-app.herokuapp.com/users: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
And this is my code:
export function fetchMicros() {
return dispatch => {
const url = "https://name-app.herokuapp.com/users";
return fetch(url, {
method: 'GET',
mode: 'cors',
headers: { 'Content-Type': 'text' },
})
.then(handleErrors)
.then(res => res.json())
.then(micros => {
dispatch(fetchVitamins(micros));
}
)};
};
If you don't have to do any authentication nor need to pass any data, you can do a no-cors request (more information on mdn page).
fetch(url, {
mode: 'no-cors',
})
If you do need cookies or some kind of authentication, then you need to make the server accept your domain and request methods on the preflight response.
In the event that you don't have access to change that on the server, you can create a nodejs server that will handle the calls for you, bypassing any cors checks (only browser cares about cors, servers don't).
I am experiencing strange issue with Axios post while doing CORS Requests.
When i make the call using the following code
export function loginUser (props) {
var request = axios.post(Endpoints.LOGIN_URL,
{
'username': props.username,
'password': props.password
});
return dispatch => {
dispatch(login())
return request.then(
function (response) {
console.log('success ', response)
dispatch(loginSuccessful(response.data))
history.go('/home');
})
.catch(function (response) {
console.log('error', response)
dispatch(loginFailed(response.data))
})
}
}
When i execute this i am seeing the Response with 200 Status code in Dev Tools. The pre-flight options request and the subsequent response are working as expected. How ever the Code block that is getting executed is the catch block !!
In console i am getting the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/auth/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
In Dev tools i am getting:
Not sure why the CORS error in the console even though the Pre-Flight response has the Header "Access-Control-Allow-Origin" !!
Appreciate any help.
Access-Control-Allow-Origin header must be present in the response from http://localhost:8080/auth/login POST operation as well.
Your Access-Control-Allow-Origin is specifying port 3000 and you are connecting on port 8080. Try removing the port entirely so your allow origin header is http://localhost or even set it to * for testing.
My app uses IBM Watson Speech-to-Text, which requires an access token. From the command line I can get the access token with curl:
curl -X GET --user my-user-account:password \
--output token \
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"
When I make an HTTP request using Angular's $http service I get a CORS error:
var data = {
user: 'my-user-account:password',
output: 'token'
};
$http({
method: 'GET',
url: 'https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
data: data,
}).then(function successCallback(response) {
console.log("HTTP GET successful");
}, function errorCallback(response) {
console.log("HTTP GET failed");
});
The error message says:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:8080' is therefore not allowed
access. The response had HTTP status code 401.
As I understand, it's not possible to do CORS from Angular; CORS has to be done from the server. I know how to do CORS with Node but I'm using Firebase as the server.
Firebase has documentation about making HTTP requests with CORS. The documentation says to write this:
$scope.getIBMToken = functions.https.onRequest((req, res) => {
cors(req, res, () => {
});
});
First, that doesn't work. The error message is functions is not defined. Apparently functions isn't in the Firebase library? I call Firebase from index.html:
<script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script>
My controller injects dependencies for $firebaseArray, $firebaseAuth, and $firebaseStorage. Do I need to inject a dependency for $firebaseHttp or something like that?
Second, how do I specify the method ('GET'), the URL, and the data (my account and password)?
if you want to send credentials with angular, just set withCredentials=true. I am also using CORS with Angular v4, for your HTTP header error, you are right. Header Access-Control-Allow-Origin must be added on server side, check if you have settings in your api to allow certain domains, urls, pages, because google api's has this function, so check where you get token there should be some settings.
Here is example, how I am calling API with CORS, using typescript:
broadcastPresense(clientId: string) {
const headers = new Headers({'Content-Type':'application/json','withCredentials':'true'});
return this.http.post('http://localhost/api.php',
{
'jsonrpc': '2.0',
'method': 'somemethod',
'params': {'client_id': clientId},
'id': CommonClass.generateRandomString(16)
},{headers: headers, withCredentials:true}).map(
(res: Response) => {
console.log(res);
const data = res.json();
console.log(data);
if (data.error == null) {
return data.result;
} else if (data.error != null) {
throw data.error;
}
throw data.error;
}
).catch(
(error) => {
this.router.navigate(['/error',3],{queryParams: {desc:'Server error'}});
return Observable.throw(error);
}
);
}
Hope it helps :)
The answer is to use Cloud Functions for Firebase, which enable running Node functions from the server. Then you use the Node module request to send the HTTP request from Node.