Home > Net >  Deno oak server post body and reponse
Deno oak server post body and reponse

Time:11-11

I use oak server with Deno. But there is some problem with the response in post request. My example:

const loginEp = async (ctx, next) => {//loginEp
  if(!ctx.request.hasBody) {//if
    ctx.throw(415);
  }//if
  
  const reqBody = await ctx.request.body({ type: 'json' }).value;
 
  console.log(reqBody, typeof reqBody);
 
  ctx.response.status = 200;
  ctx.response.body = {key_one: "One"};
  ctx.response.type = "json";

 };//loginEp

const router = new Router()
router.post("/api/login", loginEp)

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

Try use:

curl --header "Content-Type: application/json" \
     --request POST \
     --data '{"login":"test","password":"test123"}' \
     http://localhost:8010/api/login

The server receives the request and prints the body to the console. But I am not getting a response from the server.

If comment const reqBody = await ctx.request.body({ type: 'json' }).value; console.log(reqBody, typeof reqBody); then I get response.

I can't understand how to get the request body on the server and respond.

CodePudding user response:

"value" on the body is also a promise, try awaiting it:

const reqBody = await (await ctx.request.body({ type: 'json' })).value;

CodePudding user response:

If I try use:

const body = await ctx.request.body({ type: 'json' });
const reqBody = await body.value;

ctx.response.body = {key_one: "One"};

I receive error:

error: Uncaught (in promise) Error: The response is not writable. throw new Error("The response is not writable.");

  • Related