javascript - Node JS。 TypeError : https. 请求不是函数

标签 javascript node.js angularjs

我正在使用 AngularJS 编写 Web 应用程序,由于 CORS 问题,我使用了 NodeJS。好吧,当我试图在我的 Node 中发出请求时,我收到了这个错误:

TypeError: https.request is not a function
at C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\index.js:56:22
at Layer.handle [as handle_request] (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\express\lib\router\route.js:137:13)
at cors (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:188:7)
at C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:224:17
at originCallback (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:214:15)
at C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:199:9)
at corsMiddleware (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\cors\lib\index.js:204:7)
at Layer.handle [as handle_request] (C:\Users\Usuario\eclipse-workspace\AgriWea\WebContent\js\node_modules\express\lib\router\layer.js:95:5)

我的 NodeJS 文件(index.js):

var express = require('express')
var cors = require('cors')
var bodyparser = require('body-parser');
var querystring = require('querystring');
var rootCas = require('ssl-root-cas/latest').create();
rootCas.addFile(__dirname + '/ssl/ovccatastromehes.crt');
const https = require('https').globalAgent.options.ca = rootCas;
var request = require('request');

var app = express()

app.use(bodyparser.urlencoded({extened:false}));
app.use(bodyparser.json()); 
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});


app.get('/space/:id', cors(), function (req, res) {
    var soapRequest = '<?xml version="1.0" encoding="utf-8"?>'
            +'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
            +'<soap:Body>'
                +'<Provincia xmlns="http://www.catastro.meh.es/"></Provincia>'
                +'<Municipio xmlns="http://www.catastro.meh.es/"></Municipio>'
                +'<SRS xmlns="http://www.catastro.meh.es/">EPSG:4326</SRS>'
                +'<RefCat xmlns="http://www.catastro.meh.es/">'+req.params.id+'</RefCat>'
            +'</soap:Body></soap:Envelope>';

    var options = {
        host: 'ovc.catastro.meh.es',
        path: '/ovcservweb/ovcswlocalizacionrc/ovccoordenadas.asmx',
        method: 'POST',
        headers : {
            "SOAPAction" : "http://tempuri.org/OVCServWeb/OVCCoordenadas/Consulta_CPMRC",
            "Content-Type": "text/xml; charset=utf-8",
            "Content-Length": Buffer.byteLength(soapRequest)}
    };

    var httpreq = https.request(options, function (response) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            console.log("body: " + chunk);
            res.send(chunk);
        });
        response.on('end', function() {
            //res.send('ok');
        });
    });

    httpreq.write(soapRequest);
    httpreq.end();
});

app.listen(8100, function () {
  console.log('CORS-enabled web server listening on port 8100')
});

我调用 Node 的服务:

.factory("catastro", function($http, $sce) {
    /*
     *  INICIALIZACIÓN DE VARIABLES
    */
    var url = 'http://localhost:8100/space/';
    var cat = {};

    /*
     *  FUNCIONES
    */
    // Obtener XML por referencia catastral
    cat.leerReferenciaCatastral = function(rc) {
        var urladd = url + rc;
        return $http.get(urladd)
        .then(function(respuesta) {
            return respuesta.data;
        });
    };

    return cat;
})

这是我第一次使用 NodeJS,我有点不知所措。我搜索了“https”并请求是一个函数...有什么建议吗?

最佳答案

那是因为你试图在 rootCas 对象上调用函数 request:

const https = require('https').globalAgent.options.ca = rootCas;

换句话说,在这里您将 rootCas 分配给 require('https').globalAgent.options.cahttps


相反,试试这个:

const https = require('https');
https.globalAgent.options.ca = rootCas;

关于javascript - Node JS。 TypeError : https. 请求不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46692258/

相关文章:

javascript - 为什么 Mozilla Firefox 会抛出语法错误?

javascript - angularjs 表 : tr with category using ng-repeat with list

javascript - 如何用zerofill显示MySQL值

javascript - querySelectorAll() 匹配除 div 之外的所有 h1

javascript - 使用 .split() 将字符串分解为数组

node.js - Express 中的 multer-s3 上传速度慢得离谱

javascript - 添加 Angular.js Modal 会出现错误 : [$injector:unpr]

javascript - 如何使用输入在 Node.js 中运行批处理文件并获得输出

javascript - 在 Angular js 中链接 promise

javascript - 如何更改 AngularJS 中二维数组的属性?