const middleware = (req , res, next) => {console.log('Hello From Middleware');}
middleware();
app.get('/',(req, res) => {
res.send('hello world from the server');
})
Related
I have followed all documentation, token and id are correct, I have checked to send text. it works.
I want to send an image via expressjs and multer, but it doesn't work.
https://www.npmjs.com/package/discord-cloud-database
const multerMiddleware = (req, res, next) => {
const multerStorage = multer.memoryStorage();
return multer({
storage: multerStorage,
}).single("photo");
};
const uploadImageMiddleware = async (req, res, next) => {
try {
const file = req.file;
const image = await discordDatabase.uploadFile(file.buffer, file.originalname, { name: "users" });
req.image = image;
next();
} catch (error) {
next(error);
}
};
const catchAsync = (fn) => {
return (req, res, next) => {
fn(req, res, next).catch(next);
};
};
router.route("/").post(
multerMiddleware,
uploadImageMiddleware,
catchAsync(async (req, res, next) => {
try {
res.status(200).json({
status: "success",
data: {
image: req.image.url,
},
});
} catch (error) {
next(error);
}
})
);
app.listen(3000, () => console.log("server run"));
respon from postman:
respon postman
I want to successfully send an image to discord via postman.
I've created a next js custom server feature using express
Everything works fine on localhost but when deployed to google cloud
only the routes from page/api directory is working.
the /test route is not working
Server
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('/test', (req, res) => {
res.send('This is a test page')
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('Now serving on port 3000')
})
})
package.json
"start": "NODE_ENV=production node server.js",
I am trying to route in my project. I want that on clicking connect button the rooms page should get rendered. Home page is working fine but as soon I as click connect it shows Cannot GET /rooms/0b2636b5-c254-47f4-ade8-9e6b745a96d1.The code works fine when instead of routing to rooms it is on root url.
I am new to web development and I tried reading other questions on similar problem but couldn't understand.
Server side(Server.js):
const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const io = require('socket.io')(server);
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.get('/', (req, res) => {
res.render('home');
})
app.get('/rooms', (req, res) => {
res.redirect(`/rooms/${uuidV4()}`);
})
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
server.listen(3000);
Client Side(script.js)
const socket = io('/rooms');
const videoGrid = document.getElementById('video-grid');
var peer = new Peer(undefined, {
path: '/peerjs',
host: '/rooms',
port: '3000'
})
Navigation bar on home.ejs
<nav class="nav">
<li class="nav-link">
Connect
</nav>
room.ejs
<script>
const ROOM_ID = "<%=roomId%>"
</script>
<script src="/socket.io/socket.io.js" defer ></script>
<script src="script.js" defer></script>
Structure of file
public
-script.js
views
-home.ejs
-room.ejs
server.js
You're really close to it, just 1 mistake in this block:
app.get('/rooms:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
It should be:
app.get('/rooms/:room', (req, res) => {
res.render('room', { roomId: req.params.room })
})
Express documentation page here in case you need it (section Route parameters).
I am trying to test the following Express route which uses serveFiles as middleware.
import { serveFiles, setup } from 'swagger-ui-express';
export default (app: Express) => {
app.use('/api-docs/private', serveFiles(yamlFile), setup()
};
I attempted to simply mock the unit test but am getting a res.send is undefined error message
jest.mock('swagger-ui-express', () => ({
setup: jest.fn(),
serveFiles: jest.fn(),
}));
const app = express();
app.use(express.json());
describe('Test Private Route', () => {
beforeAll(() => {
jest.clearAllMocks();
const mockServe = swaggerUi.serveFiles;
(mockServe as jest.Mock).mockImplementation((req, res, next) => {
res.send({ message: 'test private' });
next();
});
swagger(app);
});
it('should retrieve something on private endpoint', async () => {
const resp = await request(app).get('/api-docs/private');
expect(resp.body).toEqual({ message: 'test private' });
});
How can I mock serveFiles so it returns resp.body?
Hi I'm working on a isomorphic react app that uses passport.js for auth.
My problem is requests can come from the client, or from the server. If the request comes from the client, it's authenticated and all is good. BUT, if the request comes from the server, then the auth fails :(
Server (lots removed for sake of clarity):
server.use('/api/data', require('./api/data'));
server.get('*', async (req, res, next) => {
await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
<div>
{component}
</div>
);
data.css = css.join('');
});
});
/api/data:
router.get('/', auth.isAuthenticated, async (req, res, next) => {
res.status(200).send({result: 'working!'});
});
Routes:
on('/route', async (state, next) => {
// RESP IS A REJECTED RESPONSE :(
const resp = await fetch('/api/data');
const data = await resp.json();
return <Component data={data} />;
});