微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

新遗物:脚本总是返回状态 400 但在 Postman 中有效

如何解决新遗物:脚本总是返回状态 400 但在 Postman 中有效

我正在尝试对我在 New Relic 中的服务进行健康检查。所以我只想每 x 分钟调用一次我的 API,看看它是否返回 200。 在 New Relic 中,我创建了一个新的合成监视器,现在我正在尝试为该监视器编写一个脚本

脚本应该向我们的服务发出发布请求并在响应中接收状态为 200 的令牌。在 Postman 中,此发布请求有效并返回令牌 + 状态 200(我将敏感字符串替换为 <...>):

curl --location --request POST <TOKEN_URL> \

--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=client_credentials' \
--data-urlencode 'client_id=<CLIENT_ID_DEV>' \
--data-urlencode 'client_secret=<CLIENT_SECRET_DEV>'

但是当我尝试用脚本重新创建它时,它总是返回状态 400 错误请求。

这是我的脚本:

var assert = require('assert');

//Defining my authentication credentials.
var IDK_TOKEN_URL = $secure.TOKEN_URL;
var CLIENT_ID = $secure.CLIENT_ID_DEV;
var CLIENT_SECRET = $secure.CLIENT_SECRET_DEV;

var options = {
url: IDK_TOKEN_URL,body: JSON.stringify({
  grant_type: 'client_credentials',client_id: CLIENT_ID,client_secret: CLIENT_SECRET,}),headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    }
};

//Define expected results using callback function.
function callback(error,response,body) {
console.log(response.statusCode + " status code")
assert.ok(response.statusCode == 200,'Expected 200 OK response');
var info = JSON.parse(body);
assert.ok(info.success == true,'Expected True results in Response Body,result was ' + info.success);
console.log("End reached");
}

//Make POST request,passing in options and callback.
$http.post(options,callback);

这是我在控制台中看到的:

new relic console

它似乎会自动将端口 443 附加到我的 url,因此请求似乎被触发到 <my url>.io/oidc/v1/token 而不是 <my url>.io:443/oidc/v1/token

当我点击上图中的“查看资源”时,我看到:

![grafik|636x148](upload://k12h5iGDkE1m2JdTSvQ8L2Qcy2j.png)

但是我使用的是post方法,为什么它说get方法是不允许的?

这是我可以在新的遗物控制台中下载的 HAR 日志:

"request": {

          "cookies": [],"headers": [

            {

              "name": "Content-Type","value": "application/x-www-form-urlencoded"

            },{

              "name": "host","value": "<my url>.io"

            },{

              "name": "content-length","value": "187"

            },{

              "name": "X-Abuse-Info","value": "Request sent by a New Relic Synthetics Monitor (https://docs.newrelic.com/docs/synthetics/new-relic-synthetics/administration/identify-synthetics-requests-your-app) - monitor id: df1817f0-fac2-49f4-a0d5-479d254dfa1a | account id: 2807718"

            },{

              "name": "X-NewRelic-Synthetics","value": "[1,2807718,\"fddc843c-8fe0-497f-bf5b-52c2805a265e\",\"b6da79b9-37ab-4a8a-a792-f3fa0f99f205\",\"df1817f0-fac2-49f4-a0d5-479d254dfa1a\"]"

            }

          ],"headeRSSize": 607,"bodySize": 187,"method": "POST","url": "<my url>.io:443/oidc/v1/token/","httpVersion": "HTTP/1.1","queryString": [],"postData": {

            "mimeType": "application/x-www-form-urlencoded","text": "{\"grant_type\":\"client_credentials\",\"client_id\":\"_SECURECREDENTIAL_\",\"client_secret\":\"_SECURECREDENTIAL_\"}","params": []

          },"_ajax": false,"_mixedContentType": "unkNown","_referrerPolicy": "","_isLinkPreload": false,"_host": "<my url>.io","_port": 443,"_path": "/oidc/v1/token/"

        },"response": {

          "cookies": [],"headers": [

            {

              "name": "Date","value": "Thu,06 May 2021 10:21:05 GMT"

            },{

              "name": "Content-Type","value": "application/json"

            },{

              "name": "Content-Length","value": "67"

            },{

              "name": "Connection","value": "close"

            },{

              "name": "Cache-Control","value": "no-cache,no-store,max-age=0,must-revalidate"

            },{

              "name": "Expires","value": "0"

            },{

              "name": "Pragma","value": "no-cache"

            },{

              "name": "Referrer-Policy","value": "origin"

            },{

              "name": "Strict-Transport-Security","value": "max-age=31536000 ; includeSubDomains"

            },{

              "name": "vary","value": "accept-encoding,origin,access-control-request-headers,access-control-request-method,accept-encoding"

            },{

              "name": "X-Content-Type-Options","value": "nosniff"

            },{

              "name": "x-frame-options","value": "DENY"

            },{

              "name": "X-Vcap-Request-Id","value": "e2006a3c-0c27-4194-6b81-d9f037158ca3"

            },{

              "name": "X-Xss-Protection","value": "1; mode=block"

            }

          ],"headeRSSize": 544,"bodySize": 67,"status": 400,"statusText": "Bad Request","content": {

            "size": 639,"compression": 572,"mimeType": "application/json","text": ""

          },"redirectURL": "","_chromeStatusText": "Bad Request","_connectionReused": false,"_fromServiceWorker": false,"_fromdiskCache": false,"_fromAppCache": false,"_fromCache": false

        },

解决方法

我不得不像 this example 一样用“form”替换“body”。

在收到令牌后,我现在还添加了对 API 的调用。最终的脚本是:

var assert = require('assert');
//Define your authentication credentials.
var TOKEN_URL = $secure.TOKEN_URL;
var MY_SERVICE_BASE_URL = $secure.MY_SERVICE_BASE_URL_DEV;
var CLIENT_ID = $secure.CLIENT_ID_DEV;
var CLIENT_SECRET = $secure.CLIENT_SECRET_DEV;

function new_relic_callback(err,response,body) {
  assert.equal(response.statusCode,200,'Expected a 200 OK response');
};

function api_request_callback(err,body) {
  var parsed_body = JSON.parse(body); 
  
  var api_request = {
    url: CONSENT_BASE_URL + '/rest of URL...',headers: {
      'Authorization': 'Bearer ' + parsed_body["access_token"]
    }
  };

  $http.get(api_request,new_relic_callback);
};

var token_request = {
  url: TOKEN_URL,form: {
    client_id: CLIENT_ID,client_secret: CLIENT_SECRET,grant_type: "client_credentials"
  },headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
    }
};

$http.post(token_request,api_request_callback);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?