(hi, just fyi before I start, I’m a beginner I don’t understand node js that well, I just found a tutorial and wanted to try it out)
This is the tutorial I’m following: https://www.youtube.com/watch?v=bB7xkRsEq-g
It’s a tutorial on how to create your own chat GPT site, I have reached the end of the “Frontend React JS component set up” section of the video.
When I run the programme I keep getting a cannot GET / error. I have tried looking up this error but none of the solutions work. I think I am getting the error because of something to do with the app.post() function in index.js (as shown below)
Here is the code so far:
index.js:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3001;
app.use(bodyParser.json());
app.use(cors());
app.post('/', (req,res) => {
res.json({
message: "submitted"
});
});
app.listen(port, () => {
console.log('Example app listening at http://localhost:'+ port);
});
App.js:
import React, {useState} from 'react';
import './App.css';
function App() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:3001/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({message}),
})
.then((res) => res.json())
.then((data) => setResponse(data.message));
};
return (
<div className="App">
<form onSubmit = {handleSubmit}>
<textarea
value = {message}
onChange = {(e)=>setMessage(e.target.value)}
></textarea>
<button type = "submit">Submit</button>
</form>
<div>{response}</div>
</div>
);
}
export default App