0

So I want to send a file to the node server which requires something from the front end. I looked around to see how I could use my app.post("",req) to retrieve confirmation of a website. However I came across a problem.

Here is the sample code:

fetch(slink, {method: "POST", headers:{
 "Content-type":"application/json"
}, body: {request: "Site Request"}}).then((resp)=>{
 return resp.json();

Thats the front end, now the back end (server side)...

app.use(bodyParser.json())

app.post("/resources",(req, resp)=>{
 console.log(req.body)
 resp.json(jsnfile) // this part works however
})

When these two are run together, the javascript on the front end isn't received on the back end, which returns an empty dictionary {}. What did I do wrong?

Glenn Parale
  • 1,464
  • 2
  • 9
  • 11

1 Answers1

0

I doesn't seem like you're sending a file whith your fetch() request. Try using this:

var input = document.querySelector('input[type="file"]');

# If you gonna take a file from the input
var data = new FormData();
data.append('file', input.files[0]);

# Asuming 'slink' is a valid url
fetch(slink, {
  method: 'POST',
  body: data
});

Possible duplicate of this issue.

EDIT

If you want to send a JSON object you just replace this line data.append('file', input.files[0]); to something like this data.append( "json", JSON.stringify(data)); and send it like previously.

Azuloo
  • 461
  • 2
  • 9