zoukankan      html  css  js  c++  java
  • Express.js----路由

    因为Express.js的不同版本的api有差异,本文的代码针对express 3.2.5

    ----package.json

    ----index.js

    1.在项目目录下建立文件,package.json,这个文件是npm安装项目所需包的依据。

    package.json

    {
      "name": "hello-world",
      "description": "hello world test app",
      "version": "0.0.1",
      "private": true,
      "dependencies": {
        "express": "3.2.5"
      }
    }

    2.在命令行窗口打开项目所以在目录通过npm安装项目依赖包,安装后出现文件夹node_modules,其中包含了express包:

    npm install
    

    3.建立文件index.js.Express提供了"routing"这个东西,其实就是,app.get(),app.post(),app.all(),这个三个函数,第一参数是路径,第一个参数是一个回调函数。

    index.js

    var express = require("express");
    var http = require("http");
    var app = express();
    
    app.all("*", function(request, response, next) {
        response.writeHead(404, { "Content-Type": "text/plain" });
        next();
    });
    
    app.get("/", function(request, response) {
        response.end("Welcome to the homepage!");
    });
    
    app.get("/about", function(request, response) {
        response.end("Welcome to the about page!");
    });
    
    app.get("*", function(request, response) {
        response.end("404!");
    });
    
    http.createServer(app).listen(3000);
    

    4.浏览器端访问URL:

    http://127.0.0.1:3000
    

    浏览器端访问URL:

    http://127.0.0.1:3000/about
    

    浏览器端访问URL:

    http://127.0.0.1:3000/*
    

      

  • 相关阅读:
    【解读】Https协议
    【解读】Http协议
    tomcat中AJP协议和HTTP协议的区别
    TOMCAT原理详解及请求过程
    Redis持久性——RDB和AOF
    redis配置文件解读
    HttpClient优化
    crontab与系统时间不一致
    天兔(Lepus)监控操作系统(OS)安装配置
    MySQL 优化之 index_merge (索引合并)
  • 原文地址:https://www.cnblogs.com/IanI/p/3994543.html
Copyright © 2011-2022 走看看