nodejs request post 请求

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

首先 安装request模块
npm install request

/**
 * Created by 26223 on 2016/12/3.
 */
'use strict'
const HttpUtils = exports;
//引入request 模块
var request = require('request')

HttpUtils.postForm = function (url, form, callback) {
    let header = getHeader();
    let option = {
        json: true,
        header : header,
        body: form
    };
    request.post(url,option, function (error, response, body) {
        resultFunction(callback,error,response,body);
    })
};

HttpUtils.postFormJson = function (url,form,callback) {
    let header = getHeader();
    let option = {
        url: url,
        method: "POST",
        json: true,
        headers: header,
        body: form
    };
    request(option,function (error, response, body) {
            resultFunction(callback,error,response,body);
    });
};

function resultFunction(callback,error, response, body){
    if (!error && response.statusCode === 200) {
        callback({success: true, msg: body});
        console.log('request is success ');
    } else {
        console.log('request is error', error);
        callback({success: false, msg: error});
    }
}

function getHeader() {
    return {
        "Content-type": "application/json; charset=UTF-8",
        "Accept": "application/json; charset=UTF-8",
        'auth': {
            'user': 'username',
            'pass': 'password',
            'sendImmediately': false
        }
    };
}
let param = {'user': 'username','pass': 'password'};
HttpUtils.postForm('http://localhost:8080/springboot/params', param, function (result) {
    console.log(result)
});

HttpUtils.postFormJson('http://localhost:8080/springboot/params', param, function (result) {
    console.log(result)
});

点这里可以跳转到人工智能网站

发表评论