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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chloesad91
    New Member
    • Sep 2022
    • 1

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

    Hi everyone
    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 :
    _____FormContac t.js

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


    FILES'S CLIENT IN ORDER :

    .htaccess :



    Code:
    <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';


    Code:
    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 :


    Code:
    {
          "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 :



    Code:
    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 :


    Code:
    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..


    Code:
    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 :

    Code:
    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 !
Working...