When I open a POST request, it doesn't work well, what's wrong with my code?
Btw. I send a POST request,but server received an OPTIONS request.
try{
const URL = config.LOGIN;
const data = await fetch(URL,{
method:"POST",
headers:{
"Accept": "application/json",
"Content-Type": "application/json"
},
body:JSON.stringify({
"a":1,
"b":2
})
}).then((response)=>{
return response.json();
});
console.log(data)
}catch(e){
// TypeError: Failed to fetch
alert(e)
}
And browser reports an error: 405: Method Not Allowed
GET request works fine
const data = await fetch(URL).then((res)=>{
return res.json()
});
Client:
405: Method Not Allowed
TypeError: Failed to fetch
Server:
[W 170505 14:20:00 web:1971] 405 OPTIONS /shundai/CoffeeManagementLogin (192.168.2.114) 1.00ms
Thanks!
Related
In the localhost:4000, the fetch works perfectly and a user is able to register
Here's the code:
const response = await fetch("/api/users/signup", {
method: "POST",
body: JSON.stringify(user),
headers: {
"Content-Type": "application/json",
},
});
const json = await response.json();
if (!response.ok) {
setError(json.error);
}
But when the app is deployed to Vercel:
I received an error stating "Uncaught (in promise) SyntaxError: Unexpected end of JSON input".
Any thoughts?
I tried changing the fetch code and it did not work.
I'm trying to access to an API using fetch however the error I receive in console:
XHR GET https://api.geoapify.com/v1/geocode/search?street=buenos%20aires&city=barcelona&country=espa%C3%B1a&lang=es&limit=1&format=json&apiKey=hereIputmyrealkey
Estado 401 Unauthorized
Versión HTTP/2
Transferido1,52 KB (tamaño 97 B)
Política de referenciastrict-origin-when-cross-origin
The fetch looks like this:
var requestOptions = {
method: 'GET',
credentials: "include"
};
let response = await fetch("https://api.geoapify.com/v1/geocode/search?street=buenos aires&city=barcelona&country=españa&lang=es&limit=1&format=json&apiKey=${MYKEY}");
When I add:
.then(error => console.log(error)
It return response undefined.
I'm working on cakephp, the url for the fetch works and outside of cakephp the fetch works too. Do I need to add something to the fetch?
(The key in my code is my actual key and the url gives a response in json format).
I tried adding:
var requestOptions = {
method: 'GET',
credentials: "include"
};
and
var requestOptions = {
method: 'GET',
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
but it gives the same error...
Use back ticks when adding ${variable}
let response = await fetch(`https://api.geoapify.com/v1/geocode/search?street=buenos aires&city=barcelona&country=españa&lang=es&limit=1&format=json&apiKey=${MYKEY}`);
I am trying to retrieve data from my own rest api. On the backend side I have express-rate-limit in use. Now I am trying to handle 429 error when it occurs. I want to display something to the user like "
Too many requests, please try again later.
How can I read the statusText of the error?
try {
const data = await fetch("http://localhost:5000/login", {
method: "POST",
body: JSON.stringify(
{
email
password
}
),
headers: {
"Accept": "application/json",
'Content-Type': 'application/json'
}
})
const result = await data.json()
if (data.status !== 200) {
throw new Error(result.detail.message)
}
console.log(result)
} catch (e) {
console.log(e) //shows: There was an error SyntaxError
}
Having an issue when trying to perform a fetch request.
fetch("https://localhost:5001/api/Blog/", {
method: "GET",
mode: "no-cors",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
credentials: "include"
}).then(response => {
console.log(response);
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
This is my request I'm sending and here is the error I'm getting.
GET https://localhost:5001/api/Blog/ net::ERR_CERT_AUTHORITY_INVALID
Anyone know how I can get around this error.
Note:
I have tested the request on 2 other computers and this worked fine.
By changing my GET request to mode: "cors" and also trusting my API in trusted root authorities. I was able to send a request to the API. Unsure why this is but it was my solution.
I have a view with permission_classes enabled
class ProjectCopyView(APIView):
permission_classes = [IsAuthor]
class IsAuthor(BasePermission):
'''Проверка права на авторство проекта'''
message = "Only the author of the project can share it"
def has_permission(self, request, view):
try:
if Project.objects.get(id=view.kwargs['project_id'], user=request.user):
return True
except:
return False
This works in postman, but when I try to repeat this request for js the error
Access to fetch at 'http://127.0.0.1:8080/api/editor/project/1/copy/' from origin 'null' has been thrown blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Django console gives 401 unautorized
async function testSizze(){
const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
})
});
const json = await res.json();
console.log(json)
}
When i disable permission_classes js the request works
fetch won’t send cookies, unless you set credentials: 'same-origin'.
const res = await fetch("http://127.0.0.1:8080/api/editor/project/1/copy/", {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
"Authorization": "Token 8fdc5648e07851c9ebe3c05f56b4c2400f2d90b9"
},
body: JSON.stringify({
"to_user": "admin#mail.ru",
"permission": ["read"],
"all_users": "False"
})
});
So maybe you are using the wrong authentication setting for django-rest-framework?
I managed to solve the problem. This project was not developed by me, and I do not quite understand why this is. I added to my permission
if request.method == 'OPTIONS':
return True