New Relic: Script always returns Status 400 but works in Postman - node.js

I'm trying to make a healthcheck for my service in New Relic. So I just want to call one of my APIs every x minutes and see if it returns 200.
In New Relic I created a new synthetic monitor and now I'm trying to write a script for that monitor.
The script is supposed to make a post request to our service and receive a token in the response with status 200. In Postman this post request works and returns the token + Status 200 (I replaced the sensitive strings with <...>):
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>'
But when I try to recreate that with the script, it always returns Status 400 Bad Request.
This is my script:
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);
This is what I see in the console:
It seems to automatically append a port 443 to my url, so instead of <my url>.io/oidc/v1/token, the request seems to get fired to <my url>.io:443/oidc/v1/token?
And when I click on "View resource" in the image above, I see:
But I'm using a post method, why is it saying anything about get method is not allowed?
This is the HAR log that I can download in the new relic console:
"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",
"httpVersion": "HTTP/1.1",
"content": {
"size": 639,
"compression": 572,
"mimeType": "application/json",
"text": ""
},
"redirectURL": "",
"_chromeStatusText": "Bad Request",
"_connectionReused": false,
"_fromServiceWorker": false,
"_fromDiskCache": false,
"_fromAppCache": false,
"_fromCache": false
},

I had to replace 'body' with 'form' like in this example.
I aslo added now the call to the API after the token was received. The final script was:
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, response, 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);

Related

GraphQL + JWT Auth + Axios isn't working and throwing a error: Error: Access denied! You need to be authorized to perform this action

I Have a backend with GraphQL and I use JWT Auth to protect it.
When I sent my GraphQL request using Insomnia, it works properly!
However when I sent using Axios it doesn't work. I'm Using React Native
Some points to consider:
Jwt isn't expired, because I can copy/paste it and use using Insomnia
I can do the same request using other methods, for example: Insomnia, direct call using other scripts
API_URI: http://localhost:3000/development/,
Axios Version (app): 0.27.2
graphql version (app): 15.5.1
graphql-tag version (app): 2.12.5
/* eslint-disable no-console */
import axios, { AxiosRequestConfig } from 'axios';
import config from '../../config';
import store from '../stores';
const api = axios.create({
baseURL: config.API_URI,
});
api.interceptors.request.use((config: AxiosRequestConfig) => {
const { token, pushNotificationToken } = store.getState().user;
config.headers.Authorization = `Bearer ${token}`;
config.headers.pushnotificationtoken = pushNotificationToken || '';
return config;
});
api.interceptors.request.use(request => {
console.log(
'\n======================= STARTING REQUEST ===========================\n',
);
console.log(JSON.stringify(request, null, 2));
console.log(
'\n======================= ENDING REQUEST ===========================\n',
);
return request;
});
api.interceptors.response.use(response => {
console.log(
'\n======================= STARTING RESPONSE ===========================\n',
);
console.log(JSON.stringify(response, null, 2));
console.log(
'\n======================= ENDING RESPONSE ===========================\n',
);
return response;
});
export async function apiRequest<ResponseType>(
body: any,
): Promise<ResponseType> {
const response = await api.post('graphql', body);
const { data } = response;
if (data.errors && data.errors.length > 0) {
throw new Error(data.errors[0].message || 'Ops! An error has occurred.');
}
return data.data;
}
export default api;
Response from backend Using Axios:
{
"data": {
"errors": [{
"message": "Access Denied",
"locations": [{
"line": 2,
"column": 3
}],
"path": [
"getAllOrders"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: Access denied! You need to be authorized to perform this action!",
" at /home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/helpers/auth-middleware.js:13:1",
" at dispatchHandler (/home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/resolvers/helpers.js:82:1)"
]
}
}
}],
"data": null
},
"status": 200,
"headers": {
"access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
"connection": "keep-alive",
"vary": "origin",
"access-control-allow-credentials": "true",
"content-length": "601",
"date": "Tue, 14 Jun 2022 15:32:37 GMT",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"keep-alive": "timeout=5"
},
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {
"FormData": null
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Authorization": "Bearer + MY JWT TOKEN GOES HERE",
"pushnotificationtoken": ""
},
"baseURL": "http://10.0.2.2:3000/development/",
"method": "post",
"url": "graphql",
"data": "{\"query\":\"query getAllOrders {\\n getAllOrders {\\n id\\n status\\n table\\n items {\\n id\\n description\\n quantity\\n priceCents\\n }\\n totalOrderPriceCents\\n createdAt\\n }\\n}\\n\"}"
},
"request": {
"UNSENT": 0,
"OPENED": 1,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"DONE": 4,
"readyState": 4,
"status": 200,
"timeout": 0,
"withCredentials": true,
"upload": {},
"_aborted": false,
"_hasError": false,
"_method": "POST",
"_perfKey": "network_XMLHttpRequest_http://10.0.2.2:3000/development/graphql",
"_response": "{\"errors\":[{\"message\":\"Acesso não autorizado\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"getAllOrders\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"Error: Access denied! You need to be authorized to perform this action!\",\" at /home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/helpers/auth-middleware.js:13:1\",\" at dispatchHandler (/home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/resolvers/helpers.js:82:1)\"]}}}],\"data\":null}\n",
"_url": "http://10.0.2.2:3000/development/graphql",
"_timedOut": false,
"_trackingName": "unknown",
"_incrementalEvents": false,
"responseHeaders": {
"access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
"Connection": "keep-alive",
"vary": "origin",
"access-control-allow-credentials": "true",
"content-length": "601",
"Date": "Tue, 14 Jun 2022 15:32:37 GMT",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"Keep-Alive": "timeout=5"
},
"_requestId": null,
"_headers": {
"accept": "application/json, text/plain, */*",
"content-type": "application/json",
"authorization": "Bearer + jwt goes here",
"pushnotificationtoken": ""
},
"_responseType": "",
"_sent": true,
"_lowerCaseResponseHeaders": {
"access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
"connection": "keep-alive",
"vary": "origin",
"access-control-allow-credentials": "true",
"content-length": "601",
"date": "Tue, 14 Jun 2022 15:32:37 GMT",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"keep-alive": "timeout=5"
},
"_subscriptions": [],
"responseURL": "http://10.0.2.2:3000/development/graphql"
}
}
The same request using Insomnia:
Insomnia Timeline:
Insomnia Header
console.log(response.request):
{
"UNSENT": 0,
"OPENED": 1,
"HEADERS_RECEIVED": 2,
"LOADING": 3,
"DONE": 4,
"readyState": 4,
"status": 200,
"timeout": 0,
"withCredentials": true,
"upload": {},
"_aborted": false,
"_hasError": false,
"_method": "POST",
"_perfKey": "network_XMLHttpRequest_http://10.0.2.2:3000/development/graphql",
"_response": "{\"errors\":[{\"message\":\"Acesso não autorizado\",\"locations\":[{\"line\":2,\"column\":3}],\"path\":[\"getAllOrders\"],\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\",\"exception\":{\"stacktrace\":[\"Error: Access denied! You need to be authorized to perform this action!\",\" at /home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/helpers/auth-middleware.js:13:1\",\" at dispatchHandler (/home/agostinho/Documents/MY-MOBILE-PROJECT/v1/MY-MOBILE-PROJECT-back-end-2020/.webpack/service/src/webpack:/node_modules/type-graphql/dist/resolvers/helpers.js:82:1)\"]}}}],\"data\":null}\n",
"_url": "http://10.0.2.2:3000/development/graphql",
"_timedOut": false,
"_trackingName": "unknown",
"_incrementalEvents": false,
"responseHeaders": {
"access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
"Connection": "keep-alive",
"vary": "origin",
"access-control-allow-credentials": "true",
"content-length": "601",
"Date": "Tue, 14 Jun 2022 17:42:39 GMT",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"Keep-Alive": "timeout=5"
},
"_requestId": null,
"_headers": {
"accept": "application/json, text/plain, */*",
"content-type": "application/json",
"authorization": "Bearer eyJ........",
"pushnotificationtoken": ""
},
"_responseType": "",
"_sent": true,
"_lowerCaseResponseHeaders": {
"access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
"connection": "keep-alive",
"vary": "origin",
"access-control-allow-credentials": "true",
"content-length": "601",
"date": "Tue, 14 Jun 2022 17:42:39 GMT",
"content-type": "application/json; charset=utf-8",
"cache-control": "no-cache",
"keep-alive": "timeout=5"
},
"_subscriptions": [],
"responseURL": "http://10.0.2.2:3000/development/graphql"
}
I found the error. It was a behavior at my authorizer context!
The Insomnia was sending Authorization with the A as Uppercase, however, axios was sending authorization with the a as lowercase.
I needed to debug my backend, so I use the following to handle with that:
const Authorization = ctx.event.headers.Authorization || ctx.event.headers.authorization
Thus, my authorizer context will handle with two situations.
The final code:
export default function context (ctx: any): any {
const Authorization = ctx.event.headers.Authorization || ctx.event.headers.authorization
if (typeof Authorization !== 'undefined' && Authorization.indexOf('Bearer') > -1) {
try {
const AuthorizationToken = Authorization.replace('Bearer ', '')
const customer = jwt.verify(AuthorizationToken, process.env.JWT_CUSTOMER_SECRET) as CustomerContext
customer.devicePushNotificationToken = ctx.event.headers.pushnotificationtoken
return { customer }
} catch (err) { }
} else {
return null
}
}

How to form URLs with loopback rest connector?

I created an API endpoint like:
GET /etablissementDetails/{id}
Here is my datasources.json file:
"etablissementDetailsREST": {
"name": "etablissementDetailsREST",
"crud": false,
"connector": "rest",
"debug": false,
"options": {
"headers": {
"accept": "application/json",
"content-type": "application/json"
},
"strictSSL": false
},
"operations": [
{
"template": {
"method": "GET",
"url": "https://data.education.gouv.fr/api/records/1.0/search/?dataset=fr-en-adresse-et-geolocalisation-etablissements-premier-et-second-degre",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
},
"query": {
"q": "{id}"
},
"options": {
"strictSSL": true,
"useQuerystring": true
},
"responsePath": "$.records.*"
},
"functions": {
"{id}": ["id"]
}
}
]}
In loopback explorer, if I enter as an idea and click on Try me out (Run the GET), I am getting the following:
http://localhost:3000/api/v1/etablissementDetails/{id}?id=0593904Y
I would like the {id} to be replaced by 0593904Y directly in the URL to become http://localhost:3000/api/v1/etablissementDetails/0593904Y

Google Street View Publish return's "Photo does not have upload reference." after statusCode 200

I'm using NodeJS to upload panoramic images.
When I make #2 informed in the Google documentation, I get the following return:
Request
{
"url": "UPLOAD_URL",
"body": "/PATH_TO_PANO/pano.jpg",
"method": "POST",
"headers": {
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
"Content-Type": "image/jpeg"
}
}
Response
{
"statusCode": 200,
"body": "",
"headers": {
"x-guploader-uploadid": "AEnB2UoJt4gvmmU6gXZvWDRu4b0DUCeT5vuPKLGcZqM4Tzo9HssCLoloTgAACRmxmP0U5DDYvHXpThCjRslW80bEKLZjUjJB3QNZ5w- j0jd8jdtVnH8X0c",
"content-length": "0",
"date": "Tue, 26 Sep 2017 21:05:17 GMT",
"server": "UploadServer",
"content-type": "text/html; charset=UTF-8",
"alt-svc": "quic=\":443\"; ma=2592000; v=\"39,38,37,35\"",
"connection": "close"
},
"request": {
"uri": {
"protocol": "https:",
"slashes": true,
"auth": null,
"host": "streetviewpublish.googleapis.com",
"port": 443,
"hostname": "streetviewpublish.googleapis.com",
"hash": null,
"search": null,
"query": null,
"pathname": "/media/user/USER_ID/photo/PHOTO_ID",
"path": "/media/user/USER_ID/photo/PHOTO_ID",
"href": "https://streetviewpublish.googleapis.com/media/user/USER_ID/photo/PHOTO_ID"
},
"method": "POST",
"headers": {
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
"Content-Type": "image/jpeg",
"content-length": 45
}
}
}
But when I upload the metadata of the photo, I get the following message:
Request
{
"url": "https://streetviewpublish.googleapis.com/v1/photo?key=YOUR_API_KEY",
"method": "POST",
"headers": {
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
"Content-Type": "application/json",
"Content-Length": 9385487
},
"data": {
"uploadReference": {
"uploadUrl": "UPLOAD_URL"
},
"pose": {
"heading": 110,
"latLngPair": {
"latitude": -29.937386,
"longitude": -60.996952
}
},
"captureTime": {
"seconds": 1506448064836
}
}
}
Response
{
"error": {
"code": 400,
"message": "Photo does not have upload reference.",
"status": "INVALID_ARGUMENT"
}
}
There are not many references to basing myself and finding the problem. For that reason I would like the help of someone who may have gone through something similar.
I have replicated your issue. I've encountered this error when I didn't specify the UPLOAD_URL in the request.
{
"error": {
"code": 400,
"message": "Photo upload url does not match required format.",
"status": "INVALID_ARGUMENT",
"details": [
{
...
}
]
}
}
Make sure that you have added the UPLOAD_URL in the request. Check this documentation for more information.

How to send push notification with "npm request" to ionic API?

I tried to push notification by ionic API with "npm request". My code:
var request = require('request');
var token = '................';
var title = escapeJson('title 123');
var message = escapeJson('message 123');
var req = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token
},
data: {
"tokens": ["........"],
"profile": "pushserver",
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
}
}
}
};
I got this Error:
{"meta": {"version": "2.0.0-beta.0", "status": 422, "request_id":
"853be189-87e0-4636-b58a-aca58cef63b3"}, "error": {"message": "Invalid
JSON in request body. For empty JSON, pass '{}'.", "type":
"UnprocessableEntity", "link": null}}
Someone know what is the problem?
Thanks
I changed "data" to "body" and now it is working:
var req = {
"method": "POST",
"url": "https://api.ionic.io/push/notifications",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
"body": {
"tokens": ["........"],
"profile": "pushserver",
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
}
}
}
};

express post not reading request payload

Trying to get a post working, basically its the user profile, the whole object is sent to a angular form from express (stored in mongo), however, I can not get the route to read the data I sent back (using body parser).
First of all, the sending part is a post using angular:
$scope.saveProfile = function(empty) {
$scope.user.updateMe = false;
$http({
method: 'POST',
url: '/api/postProfile/'+$scope.user._id,
data: $scope.user
})
.success(function(data, status, headers, config) {
console.log("I updated");
})
.error(function(data, status, headers, config) {
console.log("Big fat fail that one");
});
}
This gives me the following POST:
{
"startedDateTime": "2015-06-21T06:53:50.363Z",
"time": 0,
"request": {
"method": "POST",
"url": "http://localhost:29771/api/postProfile/55841857579127018071ad97",
"httpVersion": "unknown",
"headers": [
{
"name": "Accept",
"value": "application/json, text/plain, */*"
},
{
"name": "Referer",
"value": "http://localhost:29771/internal/profile"
},
{
"name": "Origin",
"value": "http://localhost:29771"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"
},
{
"name": "Content-Type",
"value": "application/json;charset=UTF-8"
}
],
"queryString": [],
"cookies": [],
"headersSize": -1,
"bodySize": 448,
"postData": {
"mimeType": "application/json;charset=UTF-8",
"text": "{\"_id\":\"55841857579127018071ad97\",\"updateMe\":false,\"imageUrl\":\"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50\",\"familyName\":\"Bberg\",\"firstName\":\"Ben\",\"userName\":\"Ben Bberg\",\"__v\":0,\"google\":{\"email\":\"ben.bberg#cm.com\",\"name\":\"Ben Bberg\",\"token\":\"ya29.lwGTHvRHvXhnBGTYSFVztPrjlkvtq-0HenpocX0VCsUmnbMt5zpluo411-0nyCqH2xgfwO4YCTuRyA\",\"id\":\"108193570873442725868\"}}"
}
},
"response": {
"status": 0,
"statusText": "",
"httpVersion": "unknown",
"headers": [],
"cookies": [],
"content": {
"size": 0,
"mimeType": "x-unknown"
},
"redirectURL": "",
"headersSize": -1,
"bodySize": -1,
"_transferSize": 0,
"_error": "net::ERR_EMPTY_RESPONSE"
},
"cache": {},
"timings": {
"blocked": -1,
"dns": -1,
"connect": -1,
"send": 0,
"wait": 0,
"receive": 0,
"ssl": -1
},
"pageref": "page_8"
}
]
}
}
However, when I try using the body following urlencode in the router
app.post('/api/postProfile/:id', isLoggedIn, urlencodedParser, function(req, res) {
console.log("I got called here");
var id = req.params.id;
console.log("I will update " + id + " with : " + req.body);
for (var key in req.body){
console.log(key + " value: " + req.body[key]);
}
});
I get nothing, as can be seen I try to step through the object req.body for keys, but there is just nothing there it seems, below is the output log
POST /api/postProfile/55841857579127018071ad97 - - ms - -
I got called here
I will update 55841857579127018071ad97 with : [object Object]
Anyone got any suggestions?
After a lot of faffing about, I found the issue. The line that was missing was:
app.use(bodyParser.json())
The problem seems to be that if you miss that line, you get a completely empty req.body, however, once I had this it all works perfectly.
Hope this helps someone:)

Resources