• node_编写一个接口


    1、编写app.js文件

    var express = require("express");
    var app = express();
    
    app.all("*", function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OP0TIONS");
        res.header("X-Powered-By", "3.2.1");
        res.header("Content-Type", "application/json;charset=utf-8");
        next();
    });
    
    var questions = [{
        data: 213,
        num: 4545,
        age: 12
    }, {
        data: 889,
        num: 365,
        age: 13
    }];
    
    app.get('/123', function(req, res) {
        res.status(200),
            res.json(questions)
    });
    
    var server = app.listen(3000, function() {
        var host = server.address().address;
        var port = server.address().port;
    
        console.log("Example app listening at http://%s:%s", host, port);
    })

    2、安装express

    npm install express --save

    3、node环境下运行app.js

    4、创建index.html,使用jquery的ajax请求接口

    <!DOCTYPE html>
    <html>
    
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script src="jquery-2.1.0.js"></script>
        </head>
    
        <body>
            <div>超级厉害的</div>
            <script type="text/javascript">
                $.ajax({
                    type: "get",
                    url: "http://127.0.0.1:3000/123",
                    async: true,
                    success: function(res) {
                        console.log(res)
                    }
                });
            </script>
        </body>
    
    </html>
    View Code

    5、浏览器运行index.html

  • 相关阅读:
    函数作业1
    函数、装饰器、迭代器、内置方法总练习题
    疑问
    装饰器
    文件练习题1,2
    内置函数练习题和总结
    GET和POST请求的区别
    HTTP请求方法
    HTTP之状态码
    HTTP之响应消息Response
  • 原文地址:https://www.cnblogs.com/wush-1215/p/11540930.html
Copyright © 2020-2023  润新知