Getting 400 Error while Authenticating user credentials using fetch API - reactjs

I am using asp.net core as backend and react as a front-end. I am using fetch API to authenticate user credentials.
But when I am trying to log in I am getting a 400 error. Everything is working fine on the postman.
Here is my react code:
const submitLoginForm = async (e) => {
e.preventDefault();
await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {"Content-Type": "application/json"},
credentials: 'include',
body: JSON.stringify({
email,
password,
})
});
setRedirectTo(true);
};
I am calling the above function on form submit.

Just add the => Accept: "application/json" in headers section
const submitLoginForm = async (e) => {
e.preventDefault();
await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password,
})
});
setRedirectTo(true);
};

Related

React Remix not sending cookies to remote server

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();
}

DRF and Knox Authentication: Demo accounts where user doesn't have to input credentials

I'm making an app with React as the front end and am handling authentication with knox. Everything is working fine but I require the ability for users to login to premade demo accounts without inputting any credentials. I can't figure out how to do this with Knox on the backend and I can't have the login info stored in my javascript. Any ideas how to accomplish this?
Knox:
class LoginAPI(KnoxLoginView):
authentication_classes = [BasicLikeAuthentication]
def get_post_response_data(self, request, token, instance):
user = request.user
data = {
'expiry': self.format_expiry_datetime(instance.expiry),
'token': token,
'user': user.username,
'role': user.roles.assigned_role
}
return data
Front end for regular login:
const handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.currentTarget);
const credentials = btoa(`${data.get('username')}:${data.get('password')}`);
const requestOptions = {
method: "POST",
credentials: 'include',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
"Authorization": `Basic ${credentials}`
},
body: JSON.stringify({})
}
fetch('http://127.0.0.1:8000/api/login/', requestOptions)
.then(response => {
if (response.status === 401) {
setFailedLogin(true)
}
return response.json()
})
.then(data => {
localStorage.setItem('token', data['token'])
})
.then(fetchCurrentUser)
.then(() => {
localStorage.getItem('role') == "Admin"
? navigate("/manage")
: navigate("/maindash")
})
.catch(error => console.log(error))
}

How can I send a String to a web service using POST request (react native)?

Is it possible to send a String to a PHP web service using a POST request (react native)? I only find some JSON POST requests like the following:
functionName = async() => {
const response = await fetch('http://localhost/webservice.php', {
method: 'POST',
mode: 'no-corse',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
searchQuery: 'something',
})
})
const myData = await response.json();
this.setState({data: myData});
}
How can I transform this to send a String (like just one word) instead of a JSON String?
Something like
functionName = async() => {
const response = await fetch('http://localhost/webservice.php', {
method: 'POST',
mode: 'no-corse',
headers: {
Accept: 'application/json',
'Content-Type': 'text/plain'
},
body: 'Your text'
})
const myData = await response.json();
this.setState({data: myData});
}

Error of connecting with RASA POST webhook API into React web UI

This is a react server-side code to connect the RASA webhook API. I getting status as 0. but in the RASA framework working properly and sending answers for this request. the problem is I can't fetch the rerun answer of the API call.
import React, { Component } from 'react'
export const rasaAPI = async function RASA(name, dialogue) {
// POST request using fetch with error handling
await fetch('http://192.168.8.100:5005/webhooks/rest/webhook', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'charset':'UTF-8'
},
body: JSON.stringify({ "sender": name, "message": dialogue }),
})
.then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error(response.status);
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
}
This is the console error of the API request.
Correct answer :
React app:
import React, { Component } from 'react'
export const rasaAPI = async function RASA(name, dialogue) {
// POST request using fetch with error handling
await fetch('/webhook', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'charset':'UTF-8',
},
credentials: "same-origin",
body: JSON.stringify({ "sender": name, "message": dialogue }),
}).then(response => {
return response.json();
}).then(massage => {
console.log(massage);
});
}
ADD Url into package.json file.

headers are not being set into AXIOS post request

I am working on react-redux App. When i am making Api Post request to Rest Api(on CORS). Headers are not being set. But when i try this in postman it work perfectly.
this is the code:
I want to send TOKEN(for testing).
post: (endPoint, data) => {
return axios({
method: 'post',
url: `${apiPath}/${endPoint}`,
data: data,
headers: { "Content-Type": "application/json", 'TOKEN': 1111}
}).then((res) =>{
return res;
})
}

Resources