Intro
I had made a Login form.
I had deployed the frontend on Netlify here and the backend on Heroku here. This is my backend logs https://dashboard.heroku.com/apps/my-notebook-mohit/logs
My index.js is
const connectToMongo = require('./db');
const express = require('express');
connectToMongo();
var cors = require('cors')
const app = express()
const port = 5000
//to use req body
app.use(cors())
app.use(express.json())
//Available routes
app.use('/api/auth',require('./routes/auth'));
app.use('/api/notes',require('./routes/notes'));
app.listen(process.env.PORT || port , () => {
console.log(`my-notebook backend listening at http://localhost:${process.env.PORT || port}`)
})
LoginPage.js
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import imgpath from "../assets/notepic.jpg";
import { motion } from "framer-motion";
const Login = (props) => {
let history = useHistory();
const [credentials, setCredentials] = useState({ email: "", password: "" });
const onChange = (e) => {
setCredentials({ ...credentials, [e.target.name]: e.target.value });
//input mei value typed ho sake,jaise jaise value change ho vese-vese note me set ho jaye
};
const goToSignup = () => {
history.push("/signup");
};
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("http://localhost:5000/api/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: credentials.email,
password: credentials.password,
}),
});
const json = await response.json();
if (json.success === true) {
//storing the authtoken
localStorage.setItem("token", json.authToken);
props.showAlert("User logged in successfully", "info");
history.push("/");
} else {
props.showAlert("invalid Credentials", "danger");
}
console.log(json);
};
return (
.....
<form onSubmit={handleSubmit} className="login-form">
.....
....
</form>
...
...
};
export default Login;
Problem I facing
When I make a POST request on the login button from frontend deployed on Netlify, it goes to http://localhost:5000/api/auth/login
as it makes the fetch request there only , hence shows error.
What I think?
The reason I could think is that Heroku is dynamically assigning the any other port i.e. 49004 when I check from Heroku Logs and my request is sent over port 5000.
How do I add the dynamic port to the fetch request I made?