I have this method:
export const createProject = async (project) => {
fetch(`/api/projects/new/`, {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: {
'name': project
}
})
}
which calls a django backend that creates a new project with the given name. The problem is that when the api is called, django outputs BadRequest /api/projects/new/
The backend works for sure, as I tested it with postman.
What is wrong with the request made by the front end?
Related
I am trying to set up authentication with Remix as my pure frontend and a django backend.
When the user signs in successfully, the backend sends a cookie with the response and this is set in the browser redirect with remix
const signIn = async (credentials: LoginCreds) => {
try {
const response = await fetch(generateFullBackendUrl('/auth/signin'), {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'include'
});
return response;
} catch (e) {
console.log(e);
}
}
const response = await authService.signIn({
email,
password
})
const cookies = response?.headers.get('set-cookie');
if(cookies){
return redirect('profile', {
headers: {
'Set-Cookie': cookies
}
});
However when I try to make subsequent fetch calls in my loader the cookies are not sent to the backend as I would expect the browser would
await fetch(generateFullBackendUrl('api/users/me'), {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
credentials: 'include'
})
Front end is running on port 3000
Backend running on port 4000
Im wondering why the fetch request in the loader does not send the cookies with the request
You need to read the cookie header from the loader request and pass it to your fetch headers.
There’s no way Fetch can automatically know what headers to send when used server side.
There is a quick workaround but not so elegant solution:
in your loader use this:
export const loader: LoaderFunction = async({request}) => {
const response = await fetch(`/api/books?${new URLSearchParams({
limit: '10',
page: '1',
})}`, {
headers: {
'Cookie': request.headers.get('Cookie') || ''
}
});
console.log(response)
if(response.ok) return await response.json();
}
I`m trying to model an application for managing the employees of a company. My problem: I'm trying to fetch the data of a specific user, calling the API endpoint : http://dummy.restapiexample.com/api/v1/employee/3 (the 3 can be replaced by other user-ids).
When I'm calling the endpoint from Postman I get this response
But when I try to access the same resource from my React application I get this response.
Here is how I call the API endpoint
export async function getSingleEmployee() {
return fetch('http://dummy.restapiexample.com/api/v1/employee/3', {
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-type': 'application/json;charset=utf-8',
}
})
.then(response => response)
.then(data => {
console.log(data);
})}
How can I access the data as I do in the Postman request? What am I missing?
Did you try using "await" fetch.... ?
I am trying to do a fetch() method in my React Native app:
return fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
...headers
},
body: body
})
Here url is <IP address>:<port>/api/token
method is 'POST'
headers is {Content-Type: "application/x-www-form-urlencoded"}
and body is
grant_type=password&username=<username>&password=<password>&pushtoken=&primaryhost=<primary host IP>&primaryport=<primary host port>&secondaryhost=<secondary host IP>&secondaryport=<secondary host port>&osscustomer=103&deviceid=<device ID>&version=1.0&osversion=9&deviceversion=1.0
When I use these values in a Postman request, it works fine, but when I run the fetch() method in my React Native app, it gives the error e = TypeError: Network request failed at XMLHttpRequest.xhr.onerror.
Does anyone know why this might be?
change 'Accept' to Accept without single quites.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request:How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Use the following format:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Better to use axios for http/https requests:axios package
It's working fine for me. Try this it may help
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})
I implemented a redux action using axios middleware. Unfortunately the API endpoint accepts form data only, so I had to set it like this.
const saveQuery = (title, description) => {
const bodyFormData = new FormData();
bodyFormData.set('title', title);
bodyFormData.set('description', description);
return {
type: 'SAVE_ITEM',
payload: {
request: {
url: '/save',
method: 'POST',
data: bodyFormData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
},
},
};
}
However the request header's Content-Type not changing:
I tried changing case like content-type, I tried wrapping the headers into config: { headers: { 'Content-T... } } but non of them solved the problem.
How can I achieve to send the request with 'Content-Type': 'application/x-www-form-urlencoded'
I have a reactjs web app which is hosted on Azure App Services, using App Service Authentication.
My app authenticates properly and from inside the app I'm attempting to GET /.auth/me so that I can read the access tokens to use for some future API requests but am receiving a 302 in response. The response redirects to login.microsoft.com even though the first request (to load the app) has already been authenticated.
const headers = {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'credentials': 'include'
};
return (dispatch) => {
const requestOptions = {
method: 'GET',
headers: headers,
};
return fetch("/.auth/me", requestOptions)
.then(parseResponseAndHandleErrors)
.catch(error => {
console.error(error)
});
}
I think I must be missing a cookie or a header in the GET but the docs don't give much information: https://learn.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#retrieve-tokens-in-app-code
From your client code (such as a mobile app or in-browser JavaScript), send an HTTP GET request to /.auth/me. The returned JSON has the provider-specific tokens.
I have tried setting 'credentials': 'same-origin' but that didn't make any difference.
I managed to figure this out after looking in to more detail at the 'credentials' option of the fetch() API.
'credentials' : 'same-origin' should not be included in the headers, but rather as a seperate request option:
const headers = {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
};
return (dispatch) => {
const requestOptions = {
method: 'GET',
headers: headers,
'credentials': 'same-origin' //credentials go here!!!
};
return fetch("/.auth/me", requestOptions)
......
}