Im stuck at something very trivial trying to build my frontend. My main.js looks like this :
const textfield = document.getElementById('inpTextField')
const btnSendPost = document.getElementById('btnSendPost')
btnSendPost.addEventListener('click', () => {
sendData()
})
function sendData() {
let txtValue = textfield.value
console.log(txtValue)
let sendingJSON = {
"body" : `${txtValue}`
}
fetch("http://localhost:3000/post", {
method: "post",
body: JSON.stringify(sendingJSON),
headers: { "Content-Type": "application.json"}
})
.then(res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err))
}
but my backend (express 4.18) doesnt register POST request, and console gives back enigmatic :
TypeError: Failed to fetch
at <anonymous>:1:876
at sendData (main.js:17:5)
at HTMLButtonElement.<anonymous> (main.js:7:5)
index.js (backend)
const express = require('express')
const app = express()
const port = 3000
const bp = require('body-parser')
let randomJson = {
"apple" : "cider viegar"
}
app.use(bp.json())
app.use(bp.urlencoded(({ extended: true})))
app.get('/',(req,res) => {
res.json(randomJson)
})
app.post('/post', (req, res) => {
var body = req.body
console.log(body)
res.send("ok")
})
app.listen(port, () => {
console.log(`Server running on ${port}`)
})
any ideas ?