lukeed / polka

A micro web server so fast, it'll make you dance! :dancers:
MIT License
5.39k stars 172 forks source link

res.json() | json is not a function #155

Closed darklight147 closed 3 years ago

TrySound commented 3 years ago

This is express specific api which polka does not cover. Please list your middlewares so we could address the issue to the right project.

darklight147 commented 3 years ago

i only tried to user res object from polka, i didnt import express


import polka from 'polka';

const app = polka().listen(5050);

app.get('/test', (req, res) => {
    console.log('Called');
    res.json({
        status: 200,
    });
});
Called
/mnt/c/Users/Quasimodo/Desktop/polkatest/dist/index.js:10
    res.json({
        ^

TypeError: res.json is not a function
    at Array.<anonymous> (/mnt/c/Users/Quasimodo/Desktop/polkatest/dist/index.js:10:9)
    at Polka.handler (/mnt/c/Users/Quasimodo/Desktop/polkatest/node_modules/polka/index.js:92:44)
    at Server.emit (events.js:314:20)
    at parserOnIncoming (_http_server.js:781:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this co
lukeed commented 3 years ago

As @TrySound mentioned, there is no res.json by default. It doesn't exist on native the http object. Polka only serves as a router and as a middleware executor. Everything else (that isn't native) has to be brought/defined.

In the next major version of Polka, there will be an Express-compat version that has (nearly) all built-ins ready to go for the Express user.

But for now, you can do something like this:

polka()
  .use((req, res, next) => {
    res.json = d => {
      res.setHeader('content-type', 'application/json');
      res.end(JSON.stringify(d));
    };
    next();
  })
  // ...
  .get((req, res) => {
    res.json({ hello: 'world' });
  })

Closing as a duplicate of #14 Hope that helps!