0

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.

error ss

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?

1 Answers1

0

I went through your code, you've used const port = 5000 in your nodejs backend.

This must be replaced with const port = process.env.PORT || 5000

This is because heroku dynamically assigns a port number to the running application when it's deployed, so you can't set the port to a fixed number.

bruh_tf
  • 23
  • 1
  • 4
  • Ya I have seen it here https://stackoverflow.com/questions/15693192/heroku-node-js-error-web-process-failed-to-bind-to-port-within-60-seconds-of –  Jan 19 '22 at 10:25
  • are you still facing the problem after changing `const port`? – bruh_tf Jan 19 '22 at 10:30
  • But Still I am getting `ERR_CONNECTION_REFUSED` while making any post request. Youc an check the changes I made in the last 2 commits here https://github.com/mohitm15/my-notebook/commits/master/backend/index.js –  Jan 19 '22 at 10:34
  • provide a screenshot of the error – bruh_tf Jan 19 '22 at 10:55
  • already thee, i had figured out the problem and changing the whole question here, since I can not post another for 90 min due to my less rputation –  Jan 19 '22 at 11:03
  • change `http://localhost:5000` on the frontend to the new heroku url – bruh_tf Jan 19 '22 at 11:15
  • I tried to use `fetch(`https://my-notebook-mohit.herokuapp.com:${port}/api/auth/login`, {...` where port=process.env.PORT but it shows `Failed to execute 'fetch' on 'Window': Failed to parse URL from https://my-notebook-mohit.herokuapp.com:undefined/api/auth/login` You can check the last two commit here https://github.com/mohitm15/my-notebook/commits/master –  Jan 19 '22 at 11:51
  • replace it with `fetch("https://my-notebook-mohit.herokuapp.com/api/auth/login" , {` The heroku url does not require the port to be listed while fetching, heroku takes care of that – bruh_tf Jan 19 '22 at 12:03