I use react in front-end and cs-cart API in back-end.
In the following code I used axios.put() as follows:
const data = JSON.stringify({
"test1": "val1"
});
const config = {
method: 'put',
url: 'https://example.com/api/product/111',
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(res => {
console.log(res)
});
When sending a request, the browser sends a request with the OPTIONS method, which error: 405
Method Not Allowed returns.
And the original request (PUT) is not sent.
cs-cart is installed on the server. And the react project on localhost
Have you made sure to understand the error correctly i.e
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesnt support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Make sure that the server is able to understand how to interpret your request so the clients are able to proceed.
You can look at this in more detail below here.
Related
I am trying to access data from AWS api gateway. Which works fine without an api-key but after the api-key is enabled the data is not retrived from the server while it works alright with postman testing.
The error in the browser is shows as follows ->
Access to XMLHttpRequest at 'https://bvoj5hykj0.execute-api.us-east-1.amazonaws.com/test/testresource' 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.
The server-side lambda function python code is given as follows
import json
def lambda_handler(event,context):
return {
'statusCode': 200,
'headers':{
"Access-Control-Allow-Origin": "*",
"Content-Type" : "application/json",
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-api-key",
"Access-Control-Allow-Methods" : "GET"
"Content-Type" : "application/json"
},
'body': json.dumps("changes saved")
}
The react axios code to retrive the data using api-key is as follows ->
async function testAct(){
// The below code block is also been tried and returns same response
// axios.defaults.headers.common = {
// "x-api-key": "xxxxxxxxxxxxxxxxxxxxx"
// }
// const headers = {
// "Content-Type": "application/json",
// "Authorization": "xxxxxxxxx-here-is-my-api-keyxxxxx"
// };
await axios.get("here is aws-api-url-hidden",{
headers: {
"x-api-key": "xxxxxxxxx-here-is-my-api-keyxxxxx"
}
})
.then((response) => {
console.log(response);
setTestRes(response.data);})
.catch((error) => { console.log(error);});
}
The API key and API url is right [ I have checked several times ]
The postman response is alright as below ->
without api-key->
with api-key
I was trying to get the data with aws api-key in reactjs front end. The data comes just fine with postman testing but fails inside react js.
Depending on the API Gateway to Lambda integration configuration, you will also need to enable CORS for API Gateway. This will handle the preflight OPTIONS request as noted by a previous commenter. The browser will perform the OPTIONS check, but Postman (to my knowledge) will not.
A few resources to help you configure API Gateway:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
https://aws.amazon.com/blogs/compute/configuring-cors-on-amazon-api-gateway-apis/
So, I'm working on a task, which says to fetch data using Axios, but without mentioning using a server, And when I tried to fetch data using Axios I got an error. The error is:
Access to XMLHttpRequest at 'https://api.first.org/data/v1/teams' 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.
And here is my code in ASP React:
useEffect(()=>{
var config = {
method: 'get',
url: 'https://api.first.org/data/v1/teams',
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Credentials': true
},
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
},[])
So my real question is, Can I get it to work without using a server, and I want to learn if this does and can work without a server. Because it's an Open API, and using Postman it's working, but when I do request Isn't.
There are two suggestion way from me, if you want to try axios but no deployed server.
Using axios-mock-adapter, so you can perform api call without using deployed server, but you have to mock to request by yourself. https://www.npmjs.com/package/axios-mock-adapter
Self-serving server in localhost, maybe you can use json-server and access it via localhost https://www.npmjs.com/package/json-server
I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
I want to send API KEY in the headers of my request. I use fetch method like this (I use react and its in shopify module) :
fetch("https://shopify.mysite.fr/shopify/articles/1", {
method: "GET",
mode: "cors",
headers: {
"Content-Type": "application/json",
"x-auth-token":"$2y$13$Kf0P46IM19qsdqk78SuB6CeuFfnonjsdfsdgsdhYvlSsf9uttNOgdjAQnZCz6y"
}
})
.then(res => res.json())
.then(data => {
this.setState({ article: data });
console.log(data);
})
.catch(console.log);
The problem is "x-auth-token" appeared in "access-control-request-headers" field. I just have the name but not the value (the key) and my API respond 401 ...
request headers
What should I do to obtain x-auth-token in the api?
This is the standard behaviour of the CORS enabled requests.
Before an actual call is made (GET with x-auth-token header) the browser is performing CORS preflight. This usually takes a form of additional OPTIONS request with your non-standard headers being sent in access-control-request-headers header, so that during an actual call server would know that it is safe to accept this non-standard header. Your 401 probably means that your API is not configured to accept cross origin calls or that it doesn't now your domain name and therefore prevents you from accessing it.
I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.
If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.
Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
EDIT: Error images after trying out suggestions
https://i.stack.imgur.com/wp693.png
https://i.stack.imgur.com/07rSG.png
https://i.stack.imgur.com/XwZsR.png
You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.
Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
By default, fetch won't send or receive any cookies from the server,
resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option must be set). Since Aug 25, 2017. The spec changed the default
credentials policy to same-origin. Firefox changed since 61.0b13.
So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.
mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin
Try this and see where is the error happening i believe in the parsing but lets check and see
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.
I fixed the issue by allowing in my API Application for calls from my HTTP port
(i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)