javascript - 使用请求库使用自定义 header 进行 POST

标签 javascript node.js

我正在尝试使用 JS 的 request 库向 Expo 的服务器发出 POST 请求。

Expo 要求添加某些 header ,因此我继续将它们添加到名为 headers 的字典中。

    expoPushURL = "https://exp.host/--/api/v2/push/send";

    headers = {
        "accept": "application/json", 
        "accept-encoding": "gzip, deflate", 
        "content-type": "application/json"
    };

    data = JSON.stringify({
        "to": "ExponentPushToken[myDeviceToken]", 
        "sound": "default", 
        "title": "hello", 
        "body": "Hello world!"
    });

    options = {
        url: expoPushURL, 
        headers: headers, 
        method: "POST", 
        body: data, 
        json: true
    };
    request(options, function (error, response, body) {
        console.log("Response from request: ",response);
        console.log("Error from request: ", error); 

    });  

回调返回一个 undefined object 。请求模块已导入,没有任何问题。我究竟做错了什么?

我收到此错误消息:

Error from request:  { Error: getaddrinfo ENOTFOUND exp.host exp.host:443
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
  code: 'ENOTFOUND',
  errno: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'exp.host',
  host: 'exp.host',
  port: 443 }

当我使用curl或Python的requests库时,这些“设置”或参数工作得很好,但我需要这个解决方案是在JS中。话虽如此,我确信这意味着我的代码有问题。

编辑:相关的 curl 看起来像这样:

curl -H "Content-Type: application/json" -X POST https://exp.host/--/api/v2/push/send -d '{
  "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
  "title":"hello",
  "body": "world"
}'

最佳答案

header 没有问题,它们工作正常,但缺少其他内容。你的 curl 度是多少?

我已经在我的虚拟服务器上运行了你的代码,它在正文中返回了他接受的所有有趣的值。使用此代码

const expoPushURL = "http://localhost:3099";

const headers = {
    "accept": "application/json",
    "accept-encoding": "gzip, deflate",
    "content-type": "application/json"
};

const data = JSON.stringify({
    "to": "ExponentPushToken[myDeviceToken]",
    "sound": "default",
    "title": "hello",
    "body": "Hello world!"
});

const options = {
    url: expoPushURL,
    headers: headers,
    method: "POST",
    body: data,
    json: true
};

import * as request from 'request';
request(options, function (error, response, body) {
    console.log(body.received);
});

我收到了这个回复

{ body: '"{\\"to\\":\\"ExponentPushToken[myDeviceToken]\\",\\"sound\\":\\"default\\",\\"title\\":\\"hello\\",\\"body\\":\\"Hello world!\\"}"',
  method: 'POST',
  headers: 
   { accept: 'application/json',
     'accept-encoding': 'gzip, deflate',
     'content-type': 'application/json',
     host: 'localhost:3099',
     'content-length': '115',
     connection: 'close' },
  url: '/' }

如果有人只是感兴趣,我正在使用的服务器有这个代码

const http = require('http');
const _ = require('lodash');

http.createServer((request, response) => {
    const { headers, method, url } = request;
    let body = [];
    request.on('error', (err) => {
        console.error(err);
    }).on('data', (chunk) => {
        body.push(chunk);
    }).on('end', () => {
        body = Buffer.concat(body).toString();
        let bodyToSend = JSON.stringify({
            alwaysHere: 'Always here',
            received: {
                body,
                method,
                headers,
                url,
            }
        });

        if (body) {
            body = JSON.parse(body);

            if (body && _.isObject(body.control)) {
                const control = body.control;
                if (_.isNumber(control.statusCode)) {
                    response.statusCode = control.statusCode;
                }

                if (_.isArray(control.headers)) {
                    control.headers.forEach(header => {
                        response.setHeader(header.name, header.value);
                    });
                }

                if (_.isString(control.body)) {
                    bodyToSend = control.body;
                }
            }
        }

        if (!response.hasHeader('content-type')) {
            response.setHeader('Content-Type', 'application/json');
        }
        response.write(bodyToSend); // write a response to the client
        response.end(); // end the response
    });
}).listen(3099);

关于javascript - 使用请求库使用自定义 header 进行 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48209668/

相关文章:

javascript - AngularJS:在文本框中的值更改时调用 httpget

node.js - 强制从 Http 重定向到 Https

mysql - 如何在查询语句之外从mysql查询中获取值?

node.js - Azure DevOps Pipeline 中的 Docker 镜像中的单元测试

javascript - 如何对数组的所有唯一数字求和?

javascript - 在 html 文件中使用 JavaScript chop 变量

javascript - parseFloat ('4.2.2' ) 产生 4.2 而不是 NaN?

javascript - Angular 输入更新验证器

html - 外部 CSS 在 NodeJS 中不起作用

javascript - 如何获取嵌套在数组 "results"中的 "news"对象并对其进行映射?