MERN Stack ਸਿੱਖਣ ਦਾ 36ਵਾਂ ਦਿਨ
ਮੈਂ ਆਪਣੀ MERN stack ਯਾਤਰਾ ਦੇ 36ਵੇਂ ਦਿਨ 'ਤੇ ਹਾਂ।
ਕੱਲ੍ਹ ਮੈਂ ਆਪਣਾ ਪਹਿਲਾ local web server ਬਣਾਇਆ ਸੀ। ਅੱਜ ਮੈਂ backend routing 'ਤੇ ਧਿਆਨ ਕੇਂਦਰਿਤ ਕੀਤਾ।
Routing ਤੁਹਾਡੇ server ਨੂੰ ਦੱਸਦੀ ਹੈ ਕਿ ਵੱਖ-ਵੱਖ requests ਨੂੰ ਕਿਵੇਂ ਸੰਭਾਲਣਾ ਹੈ। Backend ਇੱਕ traffic controller ਵਜੋਂ ਕੰਮ ਕਰਦਾ ਹੈ। ਇਹ URL ਦੇ ਆਧਾਰ 'ਤੇ ਫੈਸਲਾ ਕਰਦਾ ਹੈ ਕਿ ਕਿਹੜਾ content ਦਿਖਾਉਣਾ ਹੈ।
ਮੈਂ req.url property ਦੀ ਵਰਤੋਂ ਕਰਨਾ ਸਿੱਖਿਆ। ਇਹ property ਉਹ path ਰੱਖਦੀ ਹੈ ਜੋ ਇੱਕ user ਆਪਣੇ browser ਵਿੱਚ ਟਾਈਪ ਕਰਦਾ ਹੈ।
ਤੁਸੀਂ users ਨੂੰ ਸਹੀ ਜਗ੍ਹਾ ਭੇਜਣ ਲਈ logical conditions ਦੀ ਵਰਤੋਂ ਕਰਦੇ ਹੋ।
ਇੱਥੇ ਦੇਖੋ ਕਿ logic ਕਿਵੇਂ ਕੰਮ ਕਰਦਾ ਹੈ:
- Server ਆ ਰਹੀ URL ਦੀ ਜਾਂਚ ਕਰਦਾ ਹੈ।
- ਜੇਕਰ URL "/" ਹੈ, ਤਾਂ server homepage ਭੇਜਦਾ ਹੈ।
- ਜੇਕਰ URL "/about" ਹੈ, ਤਾਂ server about page ਭੇਜਦਾ ਹੈ।
- ਜੇਕਰ URL ਕਿਸੇ ਨਾਲ ਵੀ ਮੇਲ ਨਹੀਂ ਖਾਂਦਾ, ਤਾਂ server 404 error ਭੇਜਦਾ ਹੈ।
ਇਹ ਪ੍ਰਕਿਰਿਆ ਤੁਹਾਡੀ application ਨੂੰ ਸੰਗਠਿਤ ਅਤੇ functional ਰੱਖਦੀ ਹੈ।
Code example:
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.end("Welcome to the Homepage!");
} else if (req.url === "/about") {
res.end("This is the About Page detailing our stack.");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404: Page Not Found!");
}
});
Source: https://dev.to/ali_hamza_589ec7b3eb6688d/day-36-of-learning-mern-stack-183m