我想建立对 api 的https请求,我在NodeJS函数中编写了以下代码行:
function getUsers() {
/**
* HOW TO Make an HTTP Call - GET
*/
// options for GET
var optionsget = {
host: 'localhost', // here only the domain name
// (no http/https !)
port: 3000,
path: '/api/users', // the rest of the url with parameters if needed
method: 'GET' // do GET
};
console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');
// do the GET request
var reqGet = https.request(optionsget, function (res) {
console.log('Requested');
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function (d) {
console.info('GET result:\n');
process.stdout.write(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error('Last error:' + e);
});
}
服务器端代码:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql = require("mysql");
var md5 = require('MD5');
var rest = require("./REST.js");
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
function REST() {
var self = this;
self.connectMysql();
}
REST.prototype.connectMysql = function () {
var self = this;
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: 'root',
database: 'oes_api',
debug: false
});
pool.getConnection(function (err, connection) {
if (err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
};
REST.prototype.configureExpress = function (connection) {
var self = this;
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var router = express.Router();
app.use('/api', router);
app.use('/', index);
app.use('/users', users);
var rest_router = new rest(router, connection, md5);
self.startServer();
};
REST.prototype.startServer = function () {
app.listen(3000, function () {
console.log("All right! I am alive at Port 3000.");
});
};
REST.prototype.stop = function (err) {
console.log("ISSUE WITH MYSQL \n" + err);
process.exit(1);
};
new REST();
但是https连接没有建立说上一个错误:错误:套接字挂断。
请你帮我解决这个错误。
答案 0 :(得分:0)
您似乎可以使用https创建服务器。请查看节点文档中的this page。
示例强>
const https = require('https');
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);