Problem between local and uploads of a server and its web application

I have a problem :

Locally my form is sent, I receive the answer by email without worries:

{status: 201, info: {…}}
FormContact.js:31 Email envoyé

On the other hand, the posting on Cpanel went well, the node js server starts perfectly, the site is reactjs is functional, but the contact form no longer works.

Error in console on the online website:

POST http://chloe-sadry.fr/register 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token ‘<’, "<!DOCTYPE "… is not valid JSON

how are my files arranged , here I noted the folders in bold and the files inside each folder in italic. I did not note all the files but only the relevant ones:

client :
__build
__public :
_____.htaccess
_____index.html
__src :
_____FormContact.js

server :
__config :
_____index.js
__routes :
_____router.js
__.env
__server.js

FILES’S CLIENT IN ORDER :

.htaccess :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l 
    RewriteRule . /index.html [L]
 </IfModule>


FormContact.js :

import React, { useState } from 'react';


const FormContact = () => {

    const [email, setEmail] = useState("")
    const [fullName, setFullName] = useState('');
    const [message, setMessage] = useState('');

    const sendEmail = async(e)=>{
        e.preventDefault()
        const res = await fetch("/register",{
            method : "POST",
            headers : {
                "Content-Type":"application/json"
            },
            body:JSON.stringify({
                fullName,
                email,
                message
            })
        });
        
        const data = await res.json();
        console.log(data);

        if(data.status === 401 || !data){
            console.log("error")
        }else{
            
            console.log("Email envoyé");
            setFullName("")
            setEmail("")
            setMessage("")
        }
    }
    return (
        <>
            
            <div className='form-contact'>
                <form>

                    <label>Prénom / Nom</label>
                    <input
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    required
                    type="text"
                    placeholder="Prénom Nom"
                    className="fullname"
                    />

                    <label htmlFor="email">Enter your email :</label>
                    <input type="email" placeholder="E-mail" value={email} onChange={(e)=>setEmail(e.target.value)} required/>
                    
                    <label>Message</label>
                    <textarea
                    required
                    placeholder="Comment puis je vous aider ?"
                    rows={3}
                    className="message"
                    value={message}
                    onChange={(e) => setMessage(e.target.value)}
                    />
                    
                    <input type="submit" value="Envoyer" onClick={sendEmail}/>

                </form>

            </div>
        
        </>
    );
};

export default FormContact;

packages.json :

{
      "name": "my_retro_website",
      "version": "0.1.0",
      "private": true,
      "homepage": "http://chloe-sadry.fr",
      "proxy": "http://localhost:8006",
      "dependencies": {
        "@testing-library/jest-dom": "^5.16.5",
        "@testing-library/react": "^13.4.0",
        "@testing-library/user-event": "^13.5.0",
        "axios": "^0.27.2",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-icons": "^4.4.0",
        "react-scripts": "5.0.1",
        "react-toastify": "^9.0.8",
        "web-vitals": "^2.1.4"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject",
        "deploy": "gh-pages -d build"
      },
      "eslintConfig": {
        "extends": [
          "react-app",
          "react-app/jest"
        ]
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      },
      "devDependencies": {
        "gh-pages": "^4.0.0"
      }
    }

FILES’S SERVER IN ORDER :

index.js IN config’s case :

module.exports = {
    port: process.env.PORT,
    local_client_app: process.env.LOCAL_CLIENT_APP,
    remote_client_app: process.env.REMOTE_CLIENT_APP,
    allowedDomains: (
        process.env.NODE_ENV === 'production' ? 
        [
        process.env.REMOTE_CLIENT_APP, 
        process.env.REMOTE_SERVER_API
    ] : [
        process.env.LOCAL_CLIENT_APP,
        process.env.LOCAL_SERVER_API
        ])
};

routers.js IN “routes”'s case :

const express = require("express");
const router = new express.Router();
const nodemailer = require("nodemailer");

router.post("/register",(req,res)=>{
    

    try {
        const { fullName,email,message} = req.body
        const transporter = nodemailer.createTransport({
            service:"gmail",
            auth:{
                user:process.env.EMAIL,
                pass:process.env.PASSWORD
            }
        });
        const mailOptions = {
            from : process.env.EMAIL,
            to : process.env.EMAIL,
            subject : "send email success",
            html :
            `<p>FullName: <b>${fullName}</b></p>
            <p>Email: <b>${email}</b></p>
            <p>Message: <i>${message}</i></p>`
        };
        transporter.sendMail(mailOptions,(error,info)=>{
            if (error) {
                console.log("Erreur", error)
            }else{
                console.log("Email envoyé" + info.response);
                res.status(201).json({status:201,info})
            }
        })
    } catch (error) {
        res.status(201).json({status:401,error})
    }
});

module.exports = router;

.env files :

I changed the email and the password to avoid any problem for my account…

EMAIL = XXXXXX
PASSWORD = XXXXXX 
PORT=8006
HOST=localhost
LOCAL_CLIENT_APP= http://localhost:3000
REMOTE_CLIENT_APP=http://chloe-sadry.fr
LOCAL_SERVER_API=http://localhost:8006
REMOTE_SERVER_API=https://api.chloe-sadry.fr

server.js :

require("dotenv").config();
const express = require("express");
const app = express();
const router = require("./routes/router");
const cors = require("cors")
const helmet = require("helmet");
const compression = require("compression");
const config = require("./config");
const http = require("http");
const server = http.createServer(app);

const {port, allowedDomains} = config;

app.use(express.json());
app.use(cors({origin:allowedDomains, credentials : true}));
app.use(router)
app.use(helmet())
app.use(compression())

app.get("/",(req,res)=>{
  res.send("server start")
})

server.listen(port,()=>{
  console.log(`server start at :${port}`)
})

Do you have a clue about the problem please? Should I give you more info? Thanks for help !

Sorry Late here, so I only took a quick look but this does not look as a valid JSON object to me

thank you for your answer! I had not paid attention to this error of inattention I will try to correct it in all the files concerned, and try again!

@Thallius I made the changes for “fullname” but it doesn’t work. Locally yes but not on the online web application

You need to learn how to use the browsers developer windows. Open them and take a look at the network tab. There you will find all requests between client and server and you can debug the data which is sent and received.

1 Like

@Thallius thanks for answering me again! I’ll look into it and try to understand my mistake!

@Thallius I apologize for bothering you again but I have trouble understanding my problem, I take the liberty of copying you what happens in the network on the browser for the same request, if you ever see where it can come from it would help me a lot… :

I added spaces after http:// an after .fr to be able to put “links”, because the site does not allow it, but basically there is none

LOCAL :

General :

  1. Request URL: http:// localhost:3000/register
  2. Request Method: POST
  3. Status Code: 201 Created
  4. Remote Address: 127.0.0.1:3000
  5. Referrer Policy: strict-origin-when-cross-origin

Response Header :

  1. access-control-allow-credentials: true
  2. Access-Control-Allow-Headers: *
  3. Access-Control-Allow-Methods: *
  4. access-control-allow-origin: http:// localhost:8006
  5. connection: close
  6. content-length: 380
  7. content-type: application/json; charset=utf-8
  8. date: Fri, 30 Sep 2022 08:55:49 GMT
  9. etag: W/“17c-mMwt8EEBjW+jOR+lXaQrErCEd5U”
  10. Vary: Origin, Accept-Encoding
  11. x-powered-by: Express

Request Headers :

  1. Accept: /
  2. Accept-Encoding: gzip, deflate, br
  3. Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
  4. Connection: keep-alive
  5. Content-Length: 39
  6. Content-Type: application/json
  7. Host: localhost:3000
  8. Origin: http:// localhost:3000
  9. Referer: http:// localhost:3000/
  10. sec-ch-ua: “Google Chrome”;v=“105”, “Not)A;Brand”;v=“8”, “Chromium”;v=“105”
  11. sec-ch-ua-mobile: ?0
  12. sec-ch-ua-platform: “macOS”
  13. Sec-Fetch-Dest: empty
  14. Sec-Fetch-Mode: cors
  15. Sec-Fetch-Site: same-origin
  16. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

THEN ONLINE :

General :

  1. Request URL: http:// chloe-sadry. fr/register
  2. Request Method: POST
  3. Status Code: 404 Not Found
  4. Remote Address: 109.234.165.67:80
  5. Referrer Policy: strict-origin-when-cross-origin

Response Headers :

  1. Connection: keep-alive
  2. Content-Length: 315
  3. Content-Type: text/html; charset=iso-8859-1
  4. Date: Fri, 30 Sep 2022 08:56:58 GMT
  5. Server: o2switch-PowerBoost-v3

Request Headers :

  1. Accept: /
  2. Accept-Encoding: gzip, deflate
  3. Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7
  4. Connection: keep-alive
  5. Content-Length: 39
  6. Content-Type:application/json
  7. Host: chloe-sadry .fr
  8. Origin: http:// chloe-sadry .fr
  9. Referer: http:// chloe-sadry .fr/
  10. User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Thank you very much for your help !

So this is telling you this url does not exists. Where does that come from?

@Thallius I put my site http://chloe-sadry.fr on line on O2switch, I pushed my front end on this domain, and I created a sub-domain api.chloe-sadry.fr for my server on this same host. the server starts well on the site. but I think that the two do not communicate as I would like .

So if your server is at http://api.chloe-sadry.fr/ and your request goes to http:// chloe-sadry. fr/register, this could not work. So you need to use another link in your frontend

@Thallius I tried to delete the line in my packages.json in the client folder “proxy: http://localhost:8006
and that made the POST request work, but another error shows up, it asks me that in the network preview: “You need to enable JavaScript to run this app.” and in the network response i have a doctype html

but in LOCAL , in the network response and preview i have my statut 201

Thank you a lot for your help !

Sorry here I have no idea. I am not very familiar with react.

At the end what I would suggest you to do is install Postman and check the backend with it sending the request one by one.

Maybe it’s also a good idea for you learn a little bit more about network request before you try to develop an react and Nodejs application, which in my eyes is the top both of complication in installation and configuration.

Sorry for the lateness of my reply, but those are valid JSON. That is a property shorthand for:

{
    "fullname": fullname,
    "email": email,
    "message": message
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.