I am running this function that should post data to my express server. The function is called when a button is clicked.
const fetchData = async () => {
const response = await fetch('http://localhost:1337/api/test', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: 'hello world'
}),
})
// const data = await response.json()
const data = await response
console.log(data)
}
Here is my express configuration
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(express.json())
app.get('/api/test', (req: any, res: any) => {
console.log(req.body)
res.json({ status: 'ok' })
})
app.listen(1337, () => {
console.log('Server started on 1337')
})
The problem is that when I click the button I receive a 404 error for the POST request and my console.log(response)
results in the following.
Response { type: "cors", url: "http://localhost:1337/api/test", redirected: false, status: 404, ok: false, statusText: "Not Found", headers: Headers, body: ReadableStream, bodyUsed: false }
body: ReadableStream { locked: false }
bodyUsed: false
headers: Headers { }
ok: false
redirected: false
status: 404
statusText: "Not Found"
type: "cors"
url: "http://localhost:1337/api/test"
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }