diff --git a/package.json b/package.json index 005b80854d..db8ef60f2e 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "husky": "^3.1.0", "jest": "^24.9.0", "lint-staged": "^10.0.0-1", + "micro-cors": "^0.1.1", "prettier": "^1.19.1", "pretty-quick": "^2.0.1", "request": "^2.88.0" diff --git a/pages/api/comments.js b/pages/api/comments.js new file mode 100644 index 0000000000..d17a7b22fd --- /dev/null +++ b/pages/api/comments.js @@ -0,0 +1,25 @@ +import Cors from 'micro-cors' +import request from 'request' + +const cors = Cors({ + allowedMethods: ['GET', 'HEAD'] +}) + +const getCommentCount = (req, res) => { + const { + query: { url } + } = req + + request(`${url}.json`, (error, response, body) => { + if (error || response.statusCode !== 200) { + res.status(404).json({ error }) + } else { + // post_count return all posts including topic itself + const count = JSON.parse(body).posts_count - 1 + + res.status(200).json({ count }) + } + }) +} + +export default cors(getCommentCount) diff --git a/server.js b/server.js index e3361061be..a71f10aafb 100644 --- a/server.js +++ b/server.js @@ -10,10 +10,9 @@ const { createServer } = require('http') const { parse } = require('url') const next = require('next') const querystring = require('querystring') -const request = require('request') const dev = process.env.NODE_ENV !== 'production' -const app = next({ dev }) +const app = next({ dev, crossOrigin: 'anonymous' }) const port = process.env.PORT || 3000 const handle = app.getRequestHandler() @@ -110,18 +109,6 @@ app.prepare().then(() => { } else { app.render(req, res, '/doc', query) } - } else if (/^\/api\/comments/i.test(pathname)) { - request(`${query.url}.json`, (error, response, body) => { - if (error || response.statusCode !== 200) { - res.write(JSON.stringify({ error })) - } else { - // post_count return all posts including topic itself - const count = JSON.parse(body).posts_count - 1 - - res.write(JSON.stringify({ count })) - } - res.end() - }) } else { handle(req, res, parsedUrl) } diff --git a/yarn.lock b/yarn.lock index 6de0e51bce..5dd0db94e6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5813,6 +5813,11 @@ merge-stream@^2.0.0: resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== +micro-cors@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/micro-cors/-/micro-cors-0.1.1.tgz#af7a480182c114ffd1ada84ad9dffc52bb4f4054" + integrity sha512-6WqIahA5sbQR1Gjexp1VuWGFDKbZZleJb/gy1khNGk18a6iN1FdTcr3Q8twaxkV5H94RjxIBjirYbWCehpMBFw== + microevent.ts@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/microevent.ts/-/microevent.ts-0.1.1.tgz#70b09b83f43df5172d0205a63025bce0f7357fa0"