I cant send correctly the body

Viewed 142

Im using an app (nodeJS) which need catch email and password in the body of request to drop a token. Im using react in frontEnd to make the post using fetch but, when i made the post using a onClick event, and i watch the console of API, the body is not correctly formed.

{ '{"email":"johndoe@gmail.com","password":"Johnismyname"}': ' ' }

The problem isn't the API because i tested it with postman and works correctly. The problem is in the react code i guess because im still learning. This is the code in react:

    import { Link } from "react-router-dom"
    import { useRef, useState } from 'react';
    export default function Login() {
    const [token, setToken] = useState('') 
    const LOGIN_API_URL = "http://localhost:3010/api/v1/users/login"
    const GET_USER_API_URL = "http://localhost:3010/api/v1/users/getuser"
    const userEmail = useRef();
    const userPassword = useRef();
    async function apiCall(email, password, tokenUrl, userUrl) {
        const body = JSON.stringify({
            email: email,
            password: password
        });
        const fetchConfig = {
            method: "POST",
            headers: {
                "Accept": "application/json",
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body
        }
        const response = await fetch(tokenUrl, fetchConfig)
        const data = await response.json()
        console.log(data);
        return setToken(data.token)
    }
    return (
        <div className="login-container">
            <div className="inputs-container">
                <h1>Login</h1>
                <input ref={userEmail} type="email" name="email" id="email" placeholder="email"/>
                <input ref={userPassword }type="password" name="password" id="password" placeholder="password" />
                <div
                    className="button-submit"
                    onClick={() => {
                        apiCall(userEmail.current.value, userPassword.current.value, LOGIN_API_URL, GET_USER_API_URL)
                    }}
                >
                    Join
                </div>
            </div>
            <h3><Link className="register hover-expands" to="/register">Register</Link></h3>
        </div>
    )
}
2 Answers

This is due to the incorrect Content-Type you have provided in the header. Substitute application/x-www-form-urlencoded with application/json to get the desired result.

const fetchConfig = {
  method: "POST",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
  },
  body,
};

Change this line of code "Content-Type": "application/x-www-form-urlencoded" to "Content-Type": "application/json"

Related