iT邦幫忙

0

node程式執行問題...

  • 分享至 

  • twitterImage

各位前輩好:
我寫了一段node程式如下:

var http = require('http');
var server = http.createServer(function (req, res) {
  switch (req.url) {
    case '/':
      res.writeHead(200, { 'Content-Type': 'text-html' });
      res.write('<html><body>This is Home Page !</body></html>');
      console.log('This is Home Page ');
      res.end();
      break;
    case '/student':
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write('<html><body>This is Student Page !</body></html>');
      console.log('This is Student Page !');
      res.end();
      break;
    case '/admin':
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.write('<html><body>This is Admin Page !</body></html>');
      console.log('This is Admin Page !');
      res.end();
      break;
    default:
      console.log('This is an invalid req !');
      res.end('This is an invalid request !');
      break;
  }
});
server.listen(5000);

當在browser輸入localhost:5000/student 在server端出現:
This is Student Page!
This is an invalid req !

想請問為何會執行default裏的程式? 謝謝.

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
㊣浩瀚星空㊣
iT邦大神 1 級 ‧ 2020-11-11 18:10:07
最佳解答

在 switch 前加上

console.log(req.url,'url');

看看是不是發送了兩次。

前輩您好:
有二次,一次是/favicon.ico,請問如何解決? 謝謝.

一般我的做法會從web server來一些特定路徑的排除。
如 .css .js這一類的。像是 favicon.ico 也是排除的做法。
瀏覽器會自動去請求 favicon.ico 這個路徑。

或是從路由下手。記得可以在設定中設定排除。
這樣就不會拿到不相關的請求了。

了解,謝謝前輩,感謝感謝.

我要發表回答

立即登入回答