Reputation: 73
I know there have been other submissions on this topic. I have looked through all of the top hits, but I still can't find a solution.
When doing a post request, I am only getting a console log of an empty object from the server. Where am I going wrong? Thanks in advance!
React form and component
import {useState} from 'react';
const StockInput = () => {
const [ticker, setTicker] = useState('')
const handleSubmit = (e) => {
e.preventDefault();
fetch(`http://localhost:5000/api/ticker`, {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify(ticker)
}).then(() => {
console.log(ticker)
})
}
return (
<form onSubmit = {handleSubmit}>
<input
type='text'
onChange={(e) => setTicker(e.target.value)}
name='tickerInput'
value={ticker}
/>
<button>Submit</button>
</form>
);
}
export default StockInput;
Express File
const express = require('express')
const app = express()
const cors = require('cors')
app.use(express.urlencoded({ extended: true }));
app.use(cors())
app.use('/api/', require('./routes/optionRoute'))
app.post('/api/ticker/', (req,res) => {
console.log(req.body)
})
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`app listening on port ${PORT}`)
})
Proxy
"name": "option_scan_next",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:5000",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
Upvotes: 0
Views: 666
Reputation: 48
Express File:
Get your value by adding the default middleware to pull out JSON body to your req.body in place of the urlencoded type.
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
FrontEnd React Component:
You need to put your ticker value in an object, not just sending the value by itself.
const handleSubmit = (e) => {
e.preventDefault();
// Add This.
const body = {data: ticker}
// End
fetch(`http://localhost:5000/api/ticker`, {
method: 'POST',
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body) // insert object into here.
}).then((res) => {
console.log(`Response: ${res}`)
})
}
Upvotes: 1