I'm trying to make a login authentication. I'm using an express server that gives a token to the user when he submits his username and password. My problem is, that when I'm submiting that data, I get the following error:
POST http://localhost:3000/api 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
This has to be an issue with both parts of my app interacting. But I have tried changing "app.get" for "app.use" or changing the "/api" to other kind of name. Couldn't solve it. I will write the routes for every file in case you think I have a routing error.
This is my node code (app/server/server.js)
const express = require('express');
const PORT = process.env.PORT || 8080;
const app = express();
const cors = require('cors');
app.use(cors());
app.get("/api", (req, res) => {
res.send({
token: 'test123'
})
});
app.listen(PORT, () => {
console.log(`Server is running on ${PORT}`)
});
This is the part of my React app that interacts with node (app/client/src/Login.js)
const loginUser = async (credentials) => {
return fetch('/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(data => data.json())
}
const Login = ({ setToken }) => {
const [username, setUserName] = useState();
const [password, setPassword] = useState();
const handleSubmit = async e => {
e.preventDefault();
const token = await loginUser({
username,
password
});
setToken(token);
}
return (
<div>Here is the login container</div>
)
A custom hook I'm using
import { useState } from 'react';
const useToken = () => {
const getToken = () => {
const tokenString = localStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token
};
const [token, setToken] = useState(getToken());
const saveToken = userToken => {
localStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};
return {
setToken: saveToken,
token
}
}
export default useToken;
Finally, my App.js (app/client/src/App.js)
const App = () => {
const { token, setToken } = useToken();
if(!token) {
return <Login setToken={setToken} />
}
return (
<>
here is my app
</>
)