Below is reactjs code
import { apiSlice } from './apiSlice.js'; const AUTH_URL = '/auth'; export const authApiSlice = apiSlice.injectEndpoints({ endpoints: (builder) => ({ login: builder.mutation({ query: (credentials) => ({ url: `${AUTH_URL}/login`, method: 'POST', body: credentials, }), }), }), overrideExisting: false, }); export const { useLoginMutation } = authApiSlice;
const baseQuery = fetchBaseQuery({
baseUrl: 'http://localhost:8080',
prepareHeaders: (headers) => {
headers.set('Content-Type', 'application/json');
return headers;
},
})
export const apiSlice = createApi({
baseQuery,
tagTypes: ['Auth'],
endpoints: (builder) => ({})
})
import { configureStore, Tuple } from '@reduxjs/toolkit'; import authReducer from './authSlice'; import {apiSlice} from '../slices/apiSlice.js' const store = configureStore({ reducer: { auth: authReducer, [apiSlice.reducerPath]: apiSlice.reducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(apiSlice.middleware), devTools: true }); export default store;
below is the handler in which api is being called and getting response, response is good, but not able to fetch or see headers in logs or console in chrome, i can see headers in postman/insomnia
const handleLogin = async () => {
if (!username || !password) {
setError('Please fill in all fields');
return;
}
setError(``)
try {
const response = await login({ username, password }).unwrap();
console.log(response)
const token = response.headers.get('Authorization');
if (token) {
localStorage.setItem('token', token);
}
dispatch(setCredentials(response.data));
navigate('/dashboard');
} catch (err) {
console.log(err)
{err.data && err.data['message'] ? setError('Login failed: ' + err.data['message']) : setError('Login failed: ' + err.status)}
}
};
Below is server’s endpoint, here i’m binding header with response and send to the client
@PostMapping("/login")
public ResponseEntity<ApiResponse> loginUser(@RequestBody User user) {
User existingUser = userService.findByUsernameAndPassword(user.getUsername());
if (existingUser == null) {
return ResponseEntity.status(401).body(new ApiResponse("User not found", null));
}
if (passwordEncoder.matches(user.getPassword(), existingUser.getPassword())) {
if (existingUser.isVerified()) {
String token = jwtUtil.generateToken(existingUser.getUsername(), existingUser.getRole());
UserDTO userDTO = userEntityToUserDTO.mapToDTO(existingUser);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
return ResponseEntity.ok().headers(headers).body(new ApiResponse("Login successful", userDTO));
} else {
return ResponseEntity.status(401).body(new ApiResponse("User not verified", null));
}
} else {
return ResponseEntity.status(401).body(new ApiResponse("Invalid credentials", null));
}
}