Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
darklight147 opened this issue Jan 16, 2021 · 3 comments
Closed

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

darklight147 opened this issue Jan 16, 2021 · 3 comments

Comments

@darklight147
Copy link

No description provided.

@TrySound
Copy link

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
Copy link
Author

darklight147 commented Jan 16, 2021

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
Copy link
Owner

lukeed commented Jan 16, 2021

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!

@lukeed lukeed closed this as completed Jan 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants