I run the axios get method to call php script.but request send twice
how to solve this problem.
myfunction:-
axios.get('http://13.233.179.174/customers_log.php',{
headers: {
'Access-Control-Allow-Origin': '*'
},
})
.then(function (response) {
$("#spinner").hide();
console.log('this is response work');
console.log(response.data);
})
.catch(function (error) {
$("#spinner").hide();
console.log(error);
})
It'a Preflight request
It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method, Access-Control-Request-Headers, and the Origin header.
Check here - https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
Related
I'm sending GET request to the same endpoint with the same headers, including the Bearer, but while i get 200 and the correct JSON as a result when calling from Postman, when i send the request using Axios in my (Vue) project i get 302.
the call from the local project , running on localhost:8080 (in case its useful) is as follows:
const { authToken, userID } = store.getters.authUser
const config = {
method: 'get',
url: '/' + userID,
headers: {
Authorization: `Bearer ${authToken}`,
'Content-Type': 'application/json'
}
}
axios(config)
.then(res => {
console.log(res)
return res
})
.catch(e => {
console.log(e)
})
while in postman all i do is create a GET request with the same url and all i add in the headers is the 'Bearer ...'
the error i get from axios is :
Error: Network Error
at createError (createError.js?2d83:16)
at XMLHttpRequest.handleError (xhr.js?b50d:87)
and response status is 302 , any idea whats going on here??
both values of userID and the authToken exists and are equal to the same values i used with postman, same goes for the url
This question already has answers here:
Axios having CORS issue
(12 answers)
Closed 3 years ago.
I'm trying to do a post request of a server but keep getting a CORS error using axios and fetch in React.
the code:
fetch('https://api/entries',
{ mode: 'no-cors',
method: 'post',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
body: JSON.stringify({
"KEY":"VALUE"
})
})
.then((response) => {
console.log(response)
})
.catch(err => console.log(err))
or
axios({
method: 'post',
url: 'https://api/entries',
headers: {
"Content-Type":"application/octet-stream",
'Access-Control-Allow-Origin': true
},
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
axios console response
Access to XMLHttpRequest at 'https://api/entries' 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.
and the another
Fetch console response
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api/entries with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Thanks
The best and easiest way is to tackle this problem is to use Proxy URL.
Like so
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios.post(PROXY_URL+URL)
.then( i => console.log(i) )
.catch(e => console.error( "Error occured! ", e));
in your case try using this like this: This should work.
const PROXY_URL = 'https://cors-anywhere.herokuapp.com/';
const URL = 'https://api/entries';
axios({
method: 'post',
url: PROXY_URL+URL,
data: {
"KEY":"VALUE"
}
})
.then(response => {
console.log(response);
})
.catch(err => console.log(err));
You can even use Proxy URL with fetch()
its depends on your backend
for example, if you use Django
you need to install https://github.com/ottoyiu/django-cors-headers
and add this CORS_ORIGIN_ALLOW_ALL=True in setting file
I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.
I am using express to return an api response retrieved via a request call.
router.post('/', function(req, res){
var options = {
...
}
rp(options)
.then(function (parsedBody) {
console.log(parsedBody);
res.json(parsedBody)
})
The console log displays the expected payload, also when I use Postman I also see the expected payload.
When though my client app gets the response it is:
Response {type: "cors", url: "http://localhost:3001/api/", redirected: false, status: 200, ok: true, …}
Ive tried adding CORS middleware:
app.use(function(request, response, next) {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers",
"Origin, X-Rquested-With, Content-Type, Accept");
next();
});
My client is a very simple react app using fetch:
fetch('http://localhost:3001/api/', {
method: 'POST',
dataType: 'JSON',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: data,
}).then((response) => {
console.log(response);
}).catch((response) => {
console.log('Error');
});
My react app is localhost:3000 and the express api localhost:3001, the expected payload is a very simple object...
{
athlete: {
firstname: "Matt"
...
}
}
How can I just forward on the api request response to the clients fetch success method?
The problem is not CORS related, the response within the react app needed parsing as json:
.then((response) => {
console.log(response.json());
})
I am using axios in my Vue project, and one of the calls to my api involves a POST. Both my posts and gets require that the Authorization header be set with my token. All get requests work fine, but putting the exact same headers in axios.post results in a 403.
Here is my axios code:
axios.post('https://my.example.org/myapi/meta?uname=' + uname + '&umetaid=' + post.umeta_id + '&umetavalue=' + post.meta_value, {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
This always results in a 403 error, and checking my request headers show that the Authorization header is never sent. If I change axios.post to axios.get above (and add a GET method to my api code, in addition to the existing POST,OPTIONS), it will execute just fine. I suppose I could leave it this way, but I think it is bad practice to use a GET call when one really is performing a POST. Is there something I am missing about forming a POST request with axios?
Axios Post request assumes that the second parameter is data and third parameter is config.
Axios Get request assumes that the second parameter is config while the data is appended in URL.
You are sending data in the url which should be as second parameter(For POST request).
Code Should be:
var data = {
'uname': uname,
'umetaid': post.umeta_id,
'umetavalue': post.meta_value
}
var headers = {
withCredentials: true,
headers: { 'Authorization': 'Bearer ' + mytoken }
}
axios.post('https://my.example.org/myapi/meta',data,headers)
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})