app.js
import express from "express";
import { getTokenData } from "./src/services/dbServices";
const app = express();
app.get("/api/token/:token_id", (req, res) => {
const tokenId = req.params.token_id;
const worldMetadata = getTokenData(tokenId).metadata;
res.send(worldMetadata);
});
app.use(express.static("public"));
app.get("/api/animation/:token_id", (req, res) => {});
app.listen(5000, () => {
console.log("App running on port 5000");
});
Im trying to render static files from my server to display a p5.j script. right now the public directory is being rendered from the "/" route of my server thanks to the express.static. I'd like to render the public directory only when the url matches /api/animation/:token_id. I've been trying for hours to make this work
Related
I integrated Swagger to my backend API in Express and I cannot make any Postman requests to it unless I comment out the Swagger integration with the exception of the swagger.json. file.
This is what the configuration looks like in the router/ folder,
import express from 'express';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from '../swagger/swagger.json';
const router = express.Router();
router.get('/api-docs', swaggerUi.setup(swaggerDocument));
export { router as swaggerRouter }
And this is how it's integrated in the root app.ts file:
app.get('/', (req, res) => {
res.send('Howdy!');
});
app.use(swaggerRouter, swaggerUi.serve, auth.verifyAuth);
app.use(pingRouter);
app.use(async (req, res, next) => {
const result = await auth.verifyAuth(req).catch((err) => {
return err;
});
if (result.httpCode == 200) {
res.locals.authResult = result
next()
} else {
res.send(result)
}
});
Where I can look to get the bottom of this?
I building project NuxtJs + ExpressJs(SSR type) with options as below
In file server/index.js i import API route
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const fs = require('fs')
const api = require("./routes/routes.js")(app, fs);
// Import API route
app.use('/api', api);
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
In routes/routes.js
// import other routes
const productRoutes = require("./product/products.js");
const appRouter = (app, fs) => {
// default route
app.get("/", (req, res) => {
res.send("welcome to the development api-server");
});
// // other routes
productRoutes(app, fs);
};
module.exports = appRouter;
And in product/products.js
const productRoutes = (app, fs) => {
app.get("/products", (req, res) => {});
app.post("/products", (req, res) => {});
app.put("/products/:id", (req, res) => {});
app.delete("/products/:id", (req, res) => {});
};
module.exports = productRoutes;
However, i have error TypeError: app.use() requires a middleware function. Maybe i cannot pass parameter (app, fs) when using app.use('/api', api) and need to handle Middleware.
I'm newbie with ExpressJs and Middleware. I don't know what i'm missing. I hope someone please give me a solution. Thanks very much.
I'm prototyping a NextJS implementation with the following server code:
import express from 'express';
import next from 'next';
import path from 'path';
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
dotenv.config();
app.prepare().then(() => {
const server = express();
// Custom build resources aliases
// ---------------------------------------------------------------------
server.use('/favicon.ico', express.static(path.join(__dirname, 'static', 'images', 'icons', 'favicon.ico')));
// ---------------------------------------------------------------------
// Custom/dynamic routes
// ---------------------------------------------------------------------
server.get('/p/:id', (req, res) => {
const actualPage = '/post';
const queryParams = { title: req.params.id };
app.render(req, res, actualPage, queryParams);
});
// ---------------------------------------------------------------------
// Default route
// ---------------------------------------------------------------------
server.get('*', (req, res) => handle(req, res));
// ---------------------------------------------------------------------
// Express: Listener
server.listen(process.env.WEB_PORT, () => {
console.log(`Server listening on port: ${process.env.WEB_PORT}...`);
});
}).catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
As apparent, my static assets sit in a /static/ folder. Of these, I have a favicon file at /static/images/icons/favicon.ico. I am able to visit this file using https://schandillia.com/static/images/icons/favicon.ico. However, when I try hitting https://schandillia.com/favicon, it throws a 404. Am I not using express.static() correctly?
I'm using express to serve files and everything is working but I can't get my console.log statement to show in app.get() route statment. I'm currently using app.use(express.static("public")); to serve from the public folder.
Here is the full code:
//Server static files from the public folder.
app.use(express.static("public"));
app.listen(PORT, function(){
console.log("Sever is running and listening on port: " +PORT);
});
//Establish routes
app.get('/', function (req, res) {
//res.sendFile('/student-profile');
res.send("This is the response.");
});
1) How can I get this work?
2) Also, is the index.html the first file that is looked for when serving static files from the public folder?
/* directories
public
views
app.js
*/
// create server
const express = require('express');
const app = express();
// import path
const path = require('path');
// use static directory
app.use(express.static(path.join(__dirname, 'public')));
app.get("/", (req, res, next) => {
res.send("This is the response.")
// if you want to render a template then
// in the {} you can send data with
//res.render("FileName", {})
})
app.listen(PORT, () => {
console.log("Sever is running and listening on port: " +PORT);
});
I've built a react/webpack app with a public directory dist that contains index.html and bundle.js. index.html links to the bundle with <script src="./bundle.js /> and I want to serve index.html up for all routes (as react-router handles the routing). However for /demos/:name, when name has a value I want to send a static file. For example, while /demos renderings as react component (the server sends index.html), /demos/one would be interpreted by my server as requesting /demos/one.html from the server. So far I've attempted that like this:
var express = require('express');
var app = express();
app.get("demos", (req,res) => {
res.sendFile(__dirname + "/dist/index.html")
})
app.get("demos/:name", (req,res) => {
const { name } = req.params
res.sendFile(__dirname + `./demos/${name}.html`);
})
app.use("*", express.static('dist'));
var server = app.listen(8080, function () {
var {host, port} = server.address()
console.log(`listening at http://${host}:${port}`)
})
However, I keep getting Uncaught SyntaxError: Unexpected token < in the browser console.
app.get("demos/:name", (req,res) => {
const { name } = req.params
res.sendFile(__dirname + `./demos/${name}.html`);
})
app.get("*", (req,res) => {
res.sendFile(__dirname + "/dist/index.html")
})