快捷搜索: 王者荣耀 脱发

微信开发者工具调试本地服务器(nodejs)的方法

开发者工具配置:

在开发者工具右侧的详情中的项目设置,将不校验合法域名打上勾(避免每个月只能修改五次合法域名的弊端,当然这只适用于开发者工具开发时)

index.js:

Page({
  data : {
    json : 
  },

  onLoad:function(){
    var that = this;
      wx.request({
        url: http://localhost:8888,
        method: GET,
        dataType: json,
        responseType: text,
        success: function(res) {
          console.log(res.data);
          that.setData({
            json : res.data.name + + res.data.from
          })
        },
        fail: function(res) {}
      })
  }
})

index.wxml:

<view>{
         
  {json}}</view>

本地nodejs服务器:

(server.js是单独存在的js文件,不用写在开发者工具里,要通过终端输入 node server.js打开,需要nodejs环境)

server.js:

var http = require(http);

http.createServer(function (request, response) {

    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {Content-Type: text/plain});

    // 发送响应数据 "Hello World"
    response.end({"name":"本地服务器","from":"127.0.0.1"});
}).listen(8888);

// 终端打印如下信息
console.log(Server running at http://127.0.0.1:8888/);

此服务器监听本地8888端口,并在接受请求后返回一个json数据如下:

{"name":"localhost","from":"127.0.0.1"}

测试结果如下:

1.在终端中打开server.js文件

2.本地浏览器测试127.0.0.1:8888

注意事项:开发者工具中使用wx.request时的url需要http://开头

经验分享 程序员 微信小程序 职场和发展