Javascript 如何向google map api发送http请求

Javascript 如何向google map api发送http请求,javascript,node.js,google-maps-api-3,httprequest,bad-request,Javascript,Node.js,Google Maps Api 3,Httprequest,Bad Request,这是我在node.js应用程序中发出的请求: var https = require('https'); var options = { host: 'maps.googleapis.com', path: '/maps/api/geocode/json', method: 'GET', useQuerystring: true, qs: 'address=' + "1600+Amphitheatre+Parkway,+Mountain+View,+CA

这是我在node.js应用程序中发出的请求:

var https = require('https');

var options = {
    host: 'maps.googleapis.com',
    path: '/maps/api/geocode/json',
    method: 'GET',
    useQuerystring: true,
    qs: 'address=' + "1600+Amphitheatre+Parkway,+Mountain+View,+CA" + "&key=[redacted in stack overflow post]"
};

var req = https.request(options, function(response) {
    console.log(response);
    //Uncomment the code below when you start getting valid responses
    //response.on('data', function (chunk) {
    //    console.log('BODY: ' + chunk);
    //});
});
console.log(req);
req.end();
但响应返回的状态代码为:400,状态消息为:“错误请求”。下面是完整的答复

我在请求或响应中都没有看到我的查询字符串,这似乎与我有关。我尝试过删除useQuerystring:是的,从选项中删除,这似乎没有效果。我还试着在maps.googleapis.com前面添加www

我向邮递员提出了一个成功的请求,如下所示: 收到https://maps.googleapis.com/maps/api/geocode/json?address=1600+圆形剧场+公园道,+山景,+CA&key=[在堆栈溢出柱中编辑]

如何使用https模块在节点中发出请求以获得成功响应

这是console.logreq的输出:

这是console.logres的输出:

注:我读过,这不是我的问题。我特别不应该在maps.googleapis.com前面添加www


对于稍后阅读本文的读者,一旦收到良好的响应,您可能希望阅读以下内容:

您可以尝试在URL本身中指定查询字符串:路径:'/maps/api/geocode/json'+'?'+

注意,您可以考虑使用“请求”模块。它可以通过“npm”安装

源代码可在以下位置找到:-

因此,您的代码看起来像:-

var requestify = require('requestify'); 
requestify.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=<API_KEY>').then(function(response) {

    // Get the response body
    response.getBody();
});
IMP:记住在URL中替换您自己的API_键,不带尖括号


希望这有帮助:

谢谢你的提示。我应该指定我打算使用https模块,并希望避免另一种依赖关系。@Glen,请查看Chrome开发者控制台中的“网络”选项卡,并查看HTTP请求是在哪个URL发出的。另外,您可能在“path”字段的末尾缺少一个“?”。另外,您可以尝试在URL本身中指定查询字符串,即:-path:“/maps/api/geocode/json”+“?”+我正在从服务器进行调用,它不是客户端,所以我没有访问Chrome开发工具的权限。调整请求选项以将查询字符串包含在路径中会导致良好的响应状态。非常感谢。
IncomingMessage {
  _readableState: 
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: true,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: { end: [Function: responseOnEnd] },
  _eventsCount: 1,
  _maxListeners: undefined,
  socket: 
   TLSSocket {
     _tlsOptions: 
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        ALPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: false,
     alpnProtocol: false,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events: 
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener],
        data: [Function: socketOnData] },
     _eventsCount: 10,
     connecting: false,
     _hadError: false,
     _handle: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _parent: null,
     _host: 'maps.googleapis.com',
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     destroyed: false,
     _bytesDispatched: 85,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': null,
        _headers: [],
        _url: '',
        _consumed: false,
        socket: [Circular],
        incoming: [Circular],
        outgoing: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /maps/api/geocode/json HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/maps/api/geocode/json',
        _ended: false,
        parser: [Object],
        res: [Circular] },
     read: [Function],
     _consuming: true },
  connection: 
   TLSSocket {
     _tlsOptions: 
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        ALPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: false,
     alpnProtocol: false,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events: 
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener],
        data: [Function: socketOnData] },
     _eventsCount: 10,
     connecting: false,
     _hadError: false,
     _handle: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _parent: null,
     _host: 'maps.googleapis.com',
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     destroyed: false,
     _bytesDispatched: 85,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': null,
        _headers: [],
        _url: '',
        _consumed: false,
        socket: [Circular],
        incoming: [Circular],
        outgoing: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /maps/api/geocode/json HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/maps/api/geocode/json',
        _ended: false,
        parser: [Object],
        res: [Circular] },
     read: [Function],
     _consuming: true },
  httpVersionMajor: 1,
  httpVersionMinor: 1,
  httpVersion: '1.1',
  complete: false,
  headers: 
   { 'content-type': 'application/json; charset=UTF-8',
     date: 'Sat, 20 May 2017 15:12:32 GMT',
     pragma: 'no-cache',
     expires: 'Fri, 01 Jan 1990 00:00:00 GMT',
     'cache-control': 'no-cache, must-revalidate',
     'access-control-allow-origin': '*',
     server: 'mafe',
     'x-xss-protection': '1; mode=block',
     'x-frame-options': 'SAMEORIGIN',
     'alt-svc': 'quic=":443"; ma=2592000; v="37,36,35"',
     'accept-ranges': 'none',
     vary: 'Accept-Encoding',
     connection: 'close' },
  rawHeaders: 
   [ 'Content-Type',
     'application/json; charset=UTF-8',
     'Date',
     'Sat, 20 May 2017 15:12:32 GMT',
     'Pragma',
     'no-cache',
     'Expires',
     'Fri, 01 Jan 1990 00:00:00 GMT',
     'Cache-Control',
     'no-cache, must-revalidate',
     'Access-Control-Allow-Origin',
     '*',
     'Server',
     'mafe',
     'X-XSS-Protection',
     '1; mode=block',
     'X-Frame-Options',
     'SAMEORIGIN',
     'Alt-Svc',
     'quic=":443"; ma=2592000; v="37,36,35"',
     'Accept-Ranges',
     'none',
     'Vary',
     'Accept-Encoding',
     'Connection',
     'close' ],
  trailers: {},
  rawTrailers: [],
  upgrade: false,
  url: '',
  method: null,
  statusCode: 400,
  statusMessage: 'Bad Request',
  client: 
   TLSSocket {
     _tlsOptions: 
      { pipe: null,
        secureContext: [Object],
        isServer: false,
        requestCert: true,
        rejectUnauthorized: true,
        session: undefined,
        NPNProtocols: undefined,
        ALPNProtocols: undefined,
        requestOCSP: undefined },
     _secureEstablished: true,
     _securePending: false,
     _newSessionPending: false,
     _controlReleased: true,
     _SNICallback: null,
     servername: null,
     npnProtocol: false,
     alpnProtocol: false,
     authorized: true,
     authorizationError: null,
     encrypted: true,
     _events: 
      { close: [Object],
        end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        secure: [Function],
        free: [Function: onFree],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener],
        data: [Function: socketOnData] },
     _eventsCount: 10,
     connecting: false,
     _hadError: false,
     _handle: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _parent: null,
     _host: 'maps.googleapis.com',
     _readableState: 
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     destroyed: false,
     _bytesDispatched: 85,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: undefined,
     _server: null,
     ssl: 
      TLSWrap {
        bytesRead: 608,
        _externalStream: {},
        fd: -1,
        _parent: [Object],
        _parentWrap: undefined,
        _secureContext: [Object],
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        writeQueueSize: 1,
        onhandshakestart: [Function],
        onhandshakedone: [Function],
        onocspresponse: [Function],
        onerror: [Function] },
     _requestCert: true,
     _rejectUnauthorized: true,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': null,
        _headers: [],
        _url: '',
        _consumed: false,
        socket: [Circular],
        incoming: [Circular],
        outgoing: [Object],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     _httpMessage: 
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedHeader: {},
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'GET /maps/api/geocode/json HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/maps/api/geocode/json',
        _ended: false,
        parser: [Object],
        res: [Circular] },
     read: [Function],
     _consuming: true },
  _consuming: false,
  _dumped: false,
  req: 
   ClientRequest {
     domain: null,
     _events: { prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 1,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     outputSize: 0,
     writable: true,
     _last: true,
     upgrading: false,
     chunkedEncoding: false,
     shouldKeepAlive: false,
     useChunkedEncodingByDefault: false,
     sendDate: false,
     _removedHeader: {},
     _contentLength: 0,
     _hasBody: true,
     _trailer: '',
     finished: true,
     _headerSent: true,
     socket: 
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'maps.googleapis.com',
        _readableState: [Object],
        readable: true,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 85,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [Object],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: [Object],
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true },
     connection: 
      TLSSocket {
        _tlsOptions: [Object],
        _secureEstablished: true,
        _securePending: false,
        _newSessionPending: false,
        _controlReleased: true,
        _SNICallback: null,
        servername: null,
        npnProtocol: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 10,
        connecting: false,
        _hadError: false,
        _handle: [Object],
        _parent: null,
        _host: 'maps.googleapis.com',
        _readableState: [Object],
        readable: true,
        domain: null,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: false,
        destroyed: false,
        _bytesDispatched: 85,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: undefined,
        _server: null,
        ssl: [Object],
        _requestCert: true,
        _rejectUnauthorized: true,
        parser: [Object],
        _httpMessage: [Circular],
        read: [Function],
        _consuming: true },
     _header: 'GET /maps/api/geocode/json HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n',
     _headers: { host: 'maps.googleapis.com' },
     _headerNames: { host: 'Host' },
     _onPendingData: null,
     agent: 
      Agent {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        defaultPort: 443,
        protocol: 'https:',
        options: [Object],
        requests: {},
        sockets: [Object],
        freeSockets: {},
        keepAliveMsecs: 1000,
        keepAlive: false,
        maxSockets: Infinity,
        maxFreeSockets: 256,
        maxCachedSessions: 100,
        _sessionCache: [Object] },
     socketPath: undefined,
     timeout: undefined,
     method: 'GET',
     path: '/maps/api/geocode/json',
     _ended: false,
     parser: 
      HTTPParser {
        '0': [Function: parserOnHeaders],
        '1': [Function: parserOnHeadersComplete],
        '2': [Function: parserOnBody],
        '3': [Function: parserOnMessageComplete],
        '4': null,
        _headers: [],
        _url: '',
        _consumed: false,
        socket: [Object],
        incoming: [Circular],
        outgoing: [Circular],
        maxHeaderPairs: 2000,
        onIncoming: [Function: parserOnIncomingClient] },
     res: [Circular] } }
var requestify = require('requestify'); 
requestify.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=<API_KEY>').then(function(response) {

    // Get the response body
    response.getBody();
});