启动node服务请求本地接口

1,046 阅读1分钟

1.首先就是简单的安装配置node环境这里不做陈述
2.在自己电脑中新建一个文件夹
3.在文件夹里面创建一个app.js文件
4.打开命令行输入 npm init 创建package.json文件(配上npm init 选项)

package name:                      你的项目名字叫啥
version:                          版本号
description:                       对项目的描述
entry point:                      项目的入口文件(一般你要用那个js文件作为node服务,就填写那个文件,会默认到刚刚创建的app.js)
test command:                     项目启动的时候要用什么命令来执行脚本文件(默认为node app.js)
git repository:                    如果你要将项目上传到git中的话,那么就需要填写git的仓库地址(这里就不写地址了)
keywirds:                       项目关键字(不需要写)
author:                         作者的名字(你叫啥名字)
license:                        发行项目需要的证书(不需要写)

创建完成之后的目录
npm init好的目录

5.通过 npm install express --save 安装express模块
6.将下面的代码复制到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,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});



var questions = [
    {
        data: "摸鱼摸鱼",
        num: "摸鱼摸鱼",
        age: "摸鱼摸鱼"
    },
    {
        data: "摸鱼摸鱼",
        num: "摸鱼摸鱼",
        age: "摸鱼摸鱼"
    }];

//写个接口moyu
app.get('/moyu', 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);
})

7.启动服务
node app.js
在这里插入图片描述
8.浏览器地址栏访问接口http://127.0.0.1:3000/moyu
在这里插入图片描述
9.在html发起请求,创建index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

    <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        $.ajax({
            type: 'get',
            url: 'http://127.0.0.1:3000/moyu',
            success: function (data) {
                console.log(data);
            },
            error: function () {
                console.log('error');
            }
        })
    </script>
</body>

</html>

在这里插入图片描述
有哪里不懂的随时联系博主哦