I am using google forms to make a POST request from the frontend of my app. The app has a custom form and I am using google forms to keep track of the responses. I am trying to make a POST request but I keep getting a CORS error when ever the request has been made. I have tried multiple different content-types to no avail. Was hoping someone would be able to help me out here.
Error being recieved:
Access to fetch at 'https://docs.google.com/forms/d/e/1FAIpQLScXpwaAVEzgbI7SJfLDAxduZP-3dJRvraiYgxEspA2Kof8-gA/formResponse' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Code
const google_url = "https://docs.google.com/forms/d/e/1FAIpQLScXpwaAVEzgbI7SJfLDAxduZP-3dJRvraiYgxEspA2Kof8-gA/formResponse"
const request = new Request(google_url, {
method: 'POST',
headers: {
'Accept': 'text/html; charset=utf-8',
'Content-Type': 'text/html; charset=utf-8',
},
body: JSON.stringify({
'GOOGLE-FORM ID': handleNameChange,
'GOOGLE-FORM ID': handleEmailChange,
'GOOGLE-FORM ID': handleMessageChange,
})
});
fetch(request)
.then(response => {
console.log(response)
})
.catch(err =>{
console.log(err)
})
Run the following command in your shell:
curl -s -D - \
-o /dev/null -XOPTIONS \
-H 'Origin: http:localhost:3000' \
-H 'Access-Control-Request-Method: POST' \
'https://docs.google.com/forms/d/e/1FAIpQLScXpwaAVEzgbI7SJfLDAxduZP-3dJRvraiYgxEspA2Kof8-gA/formResponse'
The output doesn't contain the required CORS response headers for the preflight access-control check to succeed, which indicates that the endpoint in question is not CORS-aware.
Short of using some (secure!) CORS proxy, there isn't much you can do on your end.
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!
I have a small express/react app. I'm running server side on port 5000 and client side on port 3000. I have the following component on the front-end:
componentDidMount() {
fetch('http://localhost:5000/auth/google',
{
method: 'GET',
headers: {'Content-Type': 'application/json'},
credentials: 'same-origin',
'Access-Control-Allow-Origin': '*'
})
.then(res => {
if (!res.ok) {
throw res;
}
return res.json()
}).then(data => {
this.setState({loading: false, data});
}).catch(err => {
console.error(err);
this.setState({loading: false, error: true});
});
}
on the back-end I have this:
router.get(
"/auth/google",
passport.authenticate("google", { scope: ['Profile','https://www.googleapis.com/auth/analytics.readonly'] })
);
router.get(
"/auth/google/callback",
passport.authenticate("google", { failureRedirect: "/error", session: false }),
function(req, res) {
var token = req.user.token;
request('https://www.googleapis.com/analytics/v3/management/accounts?access_token=' + token,
function (error, response, body) {
console.log(JSON.parse(body).items);
res.send(JSON.parse(body).items)
});
}
);
and here are the error I have:
Failed to load resource: the server responded with a status of 405 ()
and
Access to fetch at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fauth%2Fgoogle%2Fcallback&scope=Profile%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&client_id=blablabla.apps.googleusercontent.com' (redirected from 'http://localhost:5000/auth/google') from origin 'null' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
CORS security violation is triggered by your browser which:
has got React code (presumably script bundles) from one server,
is seeing attempts by this code to fetch from another server that is not telling the browser to calm down and tolerate this security violation.
Failed to load resource: the server responded with a status of 405
This means the browser attempted to contact 'another server' prior to fetch and ask if it should tolerate the security violation but 'another server' refused to talk. Technically speaking, the browser has sent HTTP request using HTTP verb OPTIONS and the server responded by indicating it doesn't support this verb.
Access to fetch at 'https://accounts.google.com/o/oauth2/
That's the actual CORS violation detected by the browser which effectively refused to execute fetch.
There are lots of recipes how to calm down the browser so that it would tolerate CORS violations. But the best apprroach is to ensure the violations won't happen so that there is no need to relax the security.
The output of a React application build are .html files and script bundles, possibly source maps. Called build artifacts. If you structure your project so that in both development and production the browser gets everything (build artifacts, API responses) from one single source e.g. Express then there will be no room for CORS issues.
This question already has an answer here:
Missing token in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel
(1 answer)
Closed 4 years ago.
i want to get data with post method from axios package and xampp sever,
i have an error when work with firefox :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/aftab/inventory3/v1/repository/all. (Reason: missing token ‘x-auth’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/aftab/inventory3/v1/repository/all. (Reason: CORS request did not succeed)
but when test it in chrome it work correctly and i don't have any error ,
my axios request code is:
let page = 1;
let config =
{
'Content-Type': 'application/x-www-form-urlencoded',
'x-auth': localStorage.getItem("token"),
};
let data = {page: page};
if (localStorage.getItem("token")) {
await axios({
method: "post",
url: "http://127.0.0.1/aftab/inventory3/v1/repository/all",
data: data,
headers: config
}).then(function (response) {
console.log(response);
}).catch(function (error) {
if (error.response) {
cosole.log(response);
} else if (error.request) {
console.log(error.request);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
} else {
localStorage.removeItem("token");
// this.history.push('/log/in');
}
in the firefox console :
firefox console
in firefox console network, only option method was sent and after it we dont have any request but in the chrome it work correct and we have a post method request after option method
change your config to look like this
let config =
{
'Content-Type': 'application/x-www-form-urlencoded',
'x-auth': localStorage.getItem("token"),
'Access-Control-Allow-Origin': '*'
};
and also enable cors on your server
when we create a build from project this is work correctly in both chrome and firefox ,because in build edition of project option method don't send and we have only post method and it work on all browsers,It's like a bug in react
I have similar issue and checked my axios version and it was 0.18.0
POST request was working fine. However, GET request was not working with similar issue you have mentioned. Then I tried with beta version.
Try this beta version of axios ie 0.19.0-beta.1
https://github.com/axios/axios/tree/v0.19.0-beta.1
It fixes in my case.
"axios": "0.19.0-beta.1"
Note : if you plan to use beta version. I hope it should work.
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"