E
E
evg_962017-09-20 15:04:30
Node.js
evg_96, 2017-09-20 15:04:30

Why not come the request body?

Why does a POST request send JSON, but it does not arrive at the server? An empty object arrives.

document.querySelector("#publish").addEventListener("submit", event => {
  event.preventDefault();

  const xhr = new XMLHttpRequest();

  xhr.open("POST", "/publish");

  xhr.send(JSON.stringify({
    message: event.target.message.value
  }));

  input.value = "";
}, false);

if (process.env.TRACE) {
  require("./libs/trace");
}

const Koa = require("koa");
const app = new Koa();
const path = require("path");
const fs = require("fs");

let clients = [];

const config = require("config");

const handlers = fs.readdirSync(path.join(__dirname, "handlers")).sort();

handlers.forEach(handler => require("./handlers/" + handler).init(app)); // + koa-bodyparser

const Router = require("koa-router");

const router = new Router();

router.get("/", async (ctx, next) => {
  ctx.body = ctx.render("./templates/index.pug");
});

router.get("/subscribe", async (ctx, next) => {
  const message = await new Promise((resolve, reject) => {
    clients.push(resolve);
  });

  ctx.body = message;
});

router.post("/publish", async (ctx, next) => {
  const message = ctx.request.body;

  console.log(message); // --------------------------------------------------------- {} Пустой объект

  if (!message) {
    ctx.throw(400);
  }

  clients.forEach(resolve => {
    resolve(message);
  });

  clients = [];

  ctx.body = "ok";
});

app.use(router.routes());

app.listen(config.get("port"));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Bukreev, 2017-09-20
@denisbookreev

Forgot to send title

xhr.setRequestHeader('Content-Type', 'application/json')

N
Negwereth, 2017-09-20
@Negwereth

body parser enabled?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question