如果您使用快递,请遵循此文档
https://expressjs.com/en/guide/routing.html
在香草Node js中,您可以执行此操作
const http = require('http');
const url = require('url');
// Routes
const router = {
/* '/myapp' route will be handled here and following function will be executed */
'myapp': function (callback) {
//we expect a callback function as argument
callback(200, { name: 'sample handler' });
//execute the callback function and pass 200 status code and a sample data which will send as response payload to user
},
'login': function(callback){
callback(200, { name: 'Login' }); //You can add your routes in this object and handle them
}
};
const server = http.createServer((req, res) => {
// Get URL
const parsedURL = url.parse(req.url, true);
// Get Path
const path = parsedURL.pathname; //This will give **http://127.0.0.1:8080/myapp **
const trimmedPath = path.replace(/^\/+|\/+$/g, '');
//This will get routes specified after base url in our case **myapp**
req.on('data', (data) => {
// streamed data. Browser will send data in stream, this func will run on each stream
});
// When Request in ended, all user requests can be handled in this event
req.on('end', () => {
// Handle Routes
const choosenHandler = router[trimmedPath]; //Check in route obj
//Send the callback function which was required
choosenHandler(function (statusCode, payload) {
// Send response to user
const payloadString = JSON.stringify(payload);
res.setHeader('Content-Type', 'text/html');
res.writeHead(statusCode);
res.write('<h1>Data: ' + payloadString + '</h1>'); //This will be sent to user
console.log('returning response');
res.end();
});
});
});
// Start the server
server.listen(3000, () => {
console.log('Server Listening to 3000 port ');
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句