I want to put the epic games output in the express js get. I have 0 experience with js, so please no hate if it doesn't make sense. XD
const EpicGamesAPI = require('epicgames-status');
const express = require('express')
const app = express()
const port = 3000
EpicGamesAPI().then(callback => {
const epicgames = console.log(callback);
})
app.get('/', (req, res) => {
res.send(epicgames)
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
epicgames in res.send(epicgames) is not in the same scope as const epicgames = console.log(callback);. You can place the EpicGamesAPI callback in the get callback:
app.get('/', (req, res) => {
EpicGamesAPI().then(callback => {
const epicgames = console.log(callback);
res.send(epicgames);
})
})
When you make the get request, the EpicGamesAPI will be called. You might want to send callback to res.send, rather than a console.log.
Related
I am using axios to practice Web Scraping by making a Web Viewer, and I noticed that the CSS Wasn't Loading.
I used this code:
console.log("Tribble-Webviewer is starting!")
const express = require('express')
const app = express()
const port = 3000
const publicDir = app.use(express.static('public'))
var cheerio = require('cheerio'); // Basically jQuery for node.js
const axios = require('axios').default;
const rp = require('request-promise');
const url = 'https://pointless.com/';
app.get('/', (req, res) => {
app.use('/static', express.static('public'))
})
app.get('/test', (req, res) => {
axios.get(url)
.then(({ data }) => res.send(data))
})
app.listen(port, () => {
console.log(`Tribble-Pro is listening on port ${port}`)
})
If you load the /test page, the CSS does not show.
Example of the CSS not loading below:
Image
I used this async function:
async function getCssTest() {
try {
const response = await axios.get(urlplusstyle);
res.send(response)
} catch (error) {
console.error(error);
}
}
I want a server side generated page in next.js to be served as a file. So I wanted to grab the rendered content inside a custom server.js file:
const express = require('express');
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get('/', async (req, res) => {
const nextResponse = await app.renderToHTML(req, res, '/', req.query);
console.log('nextResponse', nextResponse);
console.log('res.body', res.body);
});
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
Oddly enough every console.log returns null or undefined.
I thought that renderToHTML would just return the rendered HTML string. Is there any way to do this?
This one is a bit tricky but achievable.
The idea is to override res.end function in order to catch rendered HTML there. The tricky part is that Next.js gzips and streams response using the compression library that's overriding res.end somewhere in the middle of the handle function.
The compression library is initialized using the handleCompression function of the Next.js's Server object (which is accessible using the app.getServer()), so that function needs to get overridden too.
So it should be looking something like this:
const { parse } = require('url');
const next = require('next');
const express = require('express');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const port = process.env.PORT || 3000;
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('*', async (req, res) => {
const parsedUrl = parse(req.url, true);
const nextServer = await app.getServer();
const _handleCompression = nodeServer.handleCompression.bind(nodeServer);
nextServer.handleCompression = (req, res) => {
_handleCompression(req, res);
const _resEnd = res.end.bind(res)
res.end = function (payload) {
console.log('Rendered HTML: ', payload);
return _resEnd(payload);
}
}
return handle(req, res, parsedUrl);
});
server.listen(port, err => {
if (err) throw err;
console.log('> Ready on http://localhost:' + port);
});
});
After you get rendered HTML you don't have to use the saved _resEnd function. Feel free to manipulate, serve as a file, or whatever you want with it.
I create an express app like this
const express = require('express')
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.post('/close', async (_, res) => {
res.status(200);
res.end();
app.close();
});
module.exports = app;
I instantiate it in another module
const myApp = require('./app.js');
myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
I want the server to shut itself down when it receives a post request to /close. At the moment, I just get a app.close is not a function error.
I know I can close a server externally like this
const server = myApp.listen(port, () => {
console.log(`Started server on ${port}`);
});
server.close();
but I want to close the server on a post request to /close, how can I do that?
To get access to your server object, try using
req.connection.server
from within your route handler.
.close() makes the server stop listening for new connections. Already-established connections are not affected. The server object emits a 'close' event when all open connections have disconnected.
process.exit() stops your whole nodejs app.
So, this code might do what you want.
app.post('/close', (req, res, next) => {
res.status(200)
res.end()
const server = req.connection.server
if (server.listening) {
server.addEventListener('close', ev => {
console.log('server closed. See ya later alligator.')
process.exit(0)
})
console.log('closing server')
server.close()
}
});
If you need to get the server object from your app object (if getting it from your req object isn't good enough), you could put in a little middleware function like this.
app.use( function adornApp( req, res, next ) {
req.app.locals.server = req.connection.server
next()
} )
Then you'll be able to get your server from app.locals.server once your middleware is first invoked.
You could use the http-terminator package to close your server. The following should do the trick. The reason we use the http-terminator is because the server won't close if it is visited via a route.
const { createHttpTerminator } = require("http-terminator");
const { initApp, app } = require("./app.js");
const PORT = 3000;
const server = app.listen(PORT, () => {
console.log(`Started server on ${PORT}`);
});
const httpTerminator = createHttpTerminator({ server });
initApp(httpTerminator);
Inside the module:
const express = require("express");
const app = express();
const initApp = (httpTerminator) => {
app.get("/close", async (_, res) => {
res.json({ message: "we closed" });
await httpTerminator.terminate();
});
};
module.exports = { initApp, app };
I can't get my data, Post function is working fine I'm using Postman for testing it. When I put localhost:3000/api/names/2, I get this error
Can not GET /api/names/2
const express = require('express');
const app = express();
var cors =require('cors')
app.use(express.json()); app.use(cors())
const names = []
app.get('/api/names/', (req, res) => {
res.send(names);
} );
app.post('/api/names', (req, res) => {
const name = {
id: names.length,
name :req.body.name
};
names.push(name);
res.send(name);
});
app.listen(3000, () => console.log('port 3000'));
To GET
app.get('/api/names/:id', (req, res) => { res.send(names.filter(x => x.id == req.params.id););
I tried to set up jest, supertest, and express but failed. I have these 2 simple file
index.js
const express = require("express");
const app = express();
const port = 3000;
app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
and index.test.js
const express = require("express");
const app = express();
const request = require("supertest");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
when I run the test I'm getting this error.
err Error: expected 200 "OK", got 404 "Not Found"
What's wrong?
I visit localhost:3000 in my browser I can see 'Hello World!'
you should refactor index.js and create app.js
app.js
const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));
index.js
const app = require('./app')
const port = process.env.PORT
app.listen(port, () => { console.log(`listening on ${port}) . })
the reason why we restructure the code like this is we need to access to express app() but we do not want "listen" to be called.
in your test file
const request = require("supertest");
const app = require("../src/app");
describe("/", () => {
test("it says hello world", done => {
request(app)
.get("/")
.expect(200)
.end(function(err, res) {
console.log("err", err);
});
});
});
It's because app instance in your test is different from the one running in your index.js
Export app from your index.js:
const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));
module.exports = server;
And import in your test:
const server = require('./index.js');
// pass your server to test
...
request(server)
.get("/")
...