0

Testing koa.js and fetch on the client side. I am trying to post some data on the server. I am getting undefined with the code below. I am unsure why.

I have inspected this, this.request, this.req, etc and I cannot find my data from the client req?

Server

import koaRouter from 'koa-router'

// Post route
router.post('/api/upload', function *(next) {
  console.log('UPLOAD WORKS', this.req.body)
  this.status = 200
})

app
  .use(bodyParser())
  .use(router.routes())
  .use(router.allowedMethods())

The console gives me undefined.

Client

fetch('/api/upload', {
  method: 'post',
  body: 'Hello'
}).then(function(response) {
  console.log(response)
}).catch(function(err) {
  // Error :(
});
Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135

1 Answers1

-1

You should change your client fatch to use a 'FormData' object to wrap the string.

var formData = new FormData();
formData.append('json', 'Hello');

fetch('/api/upload', {
  method: 'post',
  body: formData
}).then(function(response) {
  console.log(response)
}).catch(function(err) {
  // Error :(
});
Mario Santini
  • 2,905
  • 2
  • 20
  • 27