Search code examples
javascriptnode.jsreactjsexpressheroku

Failed to execute 'fetch' on 'Window': Failed to parse URL from http://app-name.herokuapp.com:undefined/api/auth/login


I am facing an error while making the POST login request.

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 . which is working fine.

Problem I facing

When I make a POST request on the login button from frontend deployed on Netlify, it goes to http://my-notebook-mohit.herokuapp.com:${port}/api/auth/login but shows the error

Failed to execute 'fetch' on 'Window': Failed to parse URL from http://app-name.herokuapp.com:undefined/api/auth/login

My index.js

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 , () => {
  console.log(`my-notebook backend listening at http://localhost:${process.env.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();
  let port = process.env.PORT;
  ....
 
  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch(`https://my-notebook-mohit.herokuapp.com:${port}/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;

error1

What to do ??


Solution

  • When I make a POST request on the login button from frontend deployed on Netlify, it goes to http://my-notebook-mohit.herokuapp.com:${port}/api/auth/login but shows the error

    Failed to execute 'fetch' on 'Window': Failed to parse URL from http://app-name.herokuapp.com:undefined/api/auth/login
    

    As it probably should. port is undefined here.

    Netlify has no way of knowing what port Heroku assigned to your app, and Heroku has no way to inject any port information into your client-side code hosted elsewhere.

    The good news is that Netlify doesn't need to know what port Heroku assigned to your back-end app. That is the port your back-end should bind to, but it is not the port used to connect to your app. How would clients ever connect if the port changed unpredictably?

    Connect to your back-end using the standard HTTPS (or, if you must, HTTP) port. These are port 443 for HTTPS and port 80 for HTTP, but the easiest thing to do is omit the port entirely:

    https://my-notebook-mohit.herokuapp.com/api/auth/login
    

    Since we are using HTTPS here, any well-behaved client will default to port 443. This request will be received by Heroku's routers and routed to your app.

    You can, and should, use HTTPS instead of HTTP for virtually all connections these days. This is especially important for security-related requests like this login request.