I am completely new to react, and a noob in general when it comes to web development.
I am trying to follow along with this youtube video (https://www.youtube.com/watch?v=bB7xkRsEq-g&list=TLPQMDMwMTIwMjMzp8A6fEwAdQ&t=1389s the part from 19:15 to 23:11) where an api for chatgpt are being built. From the video, all that is coded is an index.js file:
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: "Hello World!"
});
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
and an App.js file:
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
However, when running node index.js all I get at localhost:3001 is Cannot GET /, while the dude at youtube gets a submit form and a button. Would be extremely thankful if anybody could enlighten me on why I just get an error, and also how I can make this app render the same as in the youtube video at 23:11?
I have tried making an index.html page connected to the app.js script for rendering, but I cannot seem to get it working. However, I am mostly cursious if the youtube video have actually skipped some steps that are not shown
CodePudding user response:
localhost:3001 is where your backend runs. When you are trying to visit localhost:3001, it initiates a GET request to the root route at this URL, GET /
. Since you have one API route which is POST /
, you see the message Cannot GET /
.
You need to visit localhost:3000 (as in the video) where your frontend React server is running to view the form.