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 program, I keep getting an error "cannot GET /
"
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
CodePudding user response:
The error doesn't necessarily have to be due to app.post
. You must have gotten cannot GET /
error when you make a get request to your backend, because there is no Get API route defined in your backend path "/
".
You can fix it either by updating your frontend request as "POST
" request (instead of GET
) or you can define a "GET
" route in the "/
" path like below.
// Simple GET API to accept GET request in "/" path
app.get("/", (req, res) => {
res.status(200).send("Hey, You are in my backend!!!");
});
CodePudding user response:
If you have post app route in your code then you should use POST. But you can also use get method from a small change you can provide app.post() ===> app.get() that gives you in image. enter image description here
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.get('/', (req,res) => { // that is the small change
res.json({
message: "submitted"
});
});
app.listen(port, () => {
console.log('Example app listening at http://localhost:' port);
});