0

I'm working on a web application, express, snowpack, and react all on node.js. Im able to load the view fine however cant seem to make requests to specific endpoints.

Here is the react component making the request to the endpoint:

import React, {useState} from 'react';
import axios from 'axios';


//form component
const MyForm = () => {
//state variable that triggers component render/handles state and variables related to 
form
const [formData, setFormData] = useState({
    username: '',
    password: ''
});

//function that handles when data in the form is changed
const handleChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};

//function that handles when the form is submitted
const handleSubmit = async (event) => {
event.preventDefault();
console.log('Form submitted on client side:', formData);
console.log("Attempting to send form data to server.");
try{
    const response = await axios.post('http://10.0.0.121:8080/api/test', formData);
    console.log('Server response: ', response.data);
}catch(error){
    console.error('Error communicating with server: ', error);
}

setFormData({username: '', password: ''});
};

//Html of the component
return(
    <form id="Lform" onSubmit={handleSubmit}>
        <table>
            <tr>
                <td><label id="Uname">Username</label></td>
                <td><input type="text" name="username" value={ formData.username } 
 onChange={handleChange} required/></td>
            </tr>
            <tr>
                <td><label id="Pword">Password</label></td>
                <td><input type="password" name="password" value={ formData.password } 
 onChange={handleChange} required/></td>
            </tr>
        </table>
      <button type="submit">Submit</button>
 </form>

);
};

The url for the endpoint you see there in the request correctly points to my server and without the /api/test it will bring up the view just fine. I have also swapped it out with just /api/test, as well as the url to the localhost. I'm fairly certain the url isn't the issue here since I can access the view just fine, not the specific endpoint I want.

Here are my express endpoints:

const express = require('express');
const cors = require('cors');
var path = require('path')
var app = express();
const router = express.Router();


router.use(cors());
router.use(express.json());

router.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'public', "index.html"));
});

router.get('/index.js', function(req, res){
    res.sendFile(path.join(__dirname,'index.js'));
});

router.get('/src/*', (req, res) =>{
     res.sendFile(path.join(__dirname, 'src', req.params[0]));
 });

router.post('/api/test', (req, res)=>{
const clientData = req.body;
res.send("Communication with server successful: ", JSON.stringify(clientData));
});

router.get('/test', (req, res) =>{
    res.sendFile(path.join(__dirname,'test.html'));
});

router.use(express.static('public'));

module.exports = router;

Im using snowpack which serves static assets like my html and css files from a /public directory, my react components serve from a /src directory. Those endpoints seem to be working just fine, unless of course snowpack isn't using the endpoints at all and just using the snowpack configuration mounts I pointed to the folders to serve the view. If that's the case I'm still not sure how to proceed making use of the express endpoints.

If you need it as well here is my app.js in my root directory which makes use of the routes:

var express = require('express');
var http = require('http');
const cors = require('cors');
//import mongoose later
var app = express();
const routes = require('./router');

app.use(cors());
app.use('/', routes);
app.use(express.json());


const server = http.createServer(app);

const port = process.env.PORT ?? 443;

server.listen(port);

console.log("root directory is: " + __dirname)

console.log(`server is on http://localhost:${port}`);

Im aware that snowpack seems to be creating the dev server, is the app.js file, the code right above this, still even creating a server?

I cant seem to reach the /test endpoint as well in my routes which is supposed to serve an html file from my root project directory. Cant reach /api/test either to process the login form data. Not sure why. Its as if any endpoint that is not related to my public or src directories serving my front end view, do not work. Or as previously mentioned it could be snowpack not using express endpoints at all, which if so what are my next steps to make use of them?

If this question is a duplicate of another question please point me in the right direction, I've searched for something similar and found little to nothing. Now granted part of it is Im not sure what to look for. I also heard that you might need to set up some kind of proxy/routing for snowpack itself, which if that is what seems to be the issue here Ill kindly refer to the snowpack documentation and sort that out.

Thanks so much for your help. If you need any further information Ill kindly provide it.

Whitewolf
  • 3
  • 5

1 Answers1

0

I seem to have solved it. The snowpack dev server was running but I wasnt running an express server. So I concurrently ran both on different ports and can now reach the endpoints. The learning journey is quite something.

Whitewolf
  • 3
  • 5