Home > database >  Changing server.js when deploying
Changing server.js when deploying

Time:01-24

I know almost nothing about NodeJS, but I am building my Portfolio website in React and I wanna include a Contact Form. I use nodemailer but there is something I don't know: I have my server.js file that is listening to port 5000 (app.listen(5000, () => console.log("Server: Running"));). Well, I have this handleSubmit function that is running when the user submits the form:

const handleSubmit = async (e) => {
  e.preventDefault();
  setButtonText("Sending...");
  let response = await fetch("http://localhost:5000/contact", {
    method: "POST",
    headers: { "Content-Type": "Application/json;charset=utf-8" },
    body: JSON.stringify(formDetails),
  });
  setButtonText("Send");
  let result = response.json();
  setFormDetails(formInitialDetails);
  if (result.code === 200)
    setStatus({ succes: true, message: "Message sebt successfully" });
  else setStatus({ succes: false, message: "Something went wrong!" });
}

And the form: <form onSubmit={handleSubmit}>...</form>

Now my question is: If my handleSubmit function is listening at http://localhost:5000/contact what am I supposed to do (to change) in order to make this React App work as I expect when I deploy it. I mean: if I deploy this with GitHub Pages or Netlify the URL will be different than http://localhost:5000/contact, right? So what I have to do before I deploy it?

CodePudding user response:

You can just use environment variable instead of let your url in your code. Like:

const response = await fetch(process.env.serverUrl, {
    method: "POST",
    headers: { "Content-Type": "Application/json;charset=utf-8" },
    body: JSON.stringify(formDetails),
  });

And then set your environment variable serverUrl in Github Pages (see how here)

CodePudding user response:

you should add the url dynamically depending of the original url of the page, you can do that with with javascript like, in your case try this:

let response = await fetch(`${window.location.protocol}//${window.location.host}/contact`, {
    method: "POST",
    headers: { "Content-Type": "Application/json;charset=utf-8" },
    body: JSON.stringify(formDetails),
  });
  • Related