Axios does not return XML error message from S3 when uploading asset over the size limit - node.js

Axios does not return XML error message from S3 when uploading asset over the size limit.
Environment
Axios Version : 0.24.0
Node.js Version: v14.17.4
OS: Mac OS 12.3
S3 is returning this XML error message when I try to uplaod an asset over teh size limit
UPLOAD FAILED. Status Code: 400. Error message:
<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>EntityTooLarge</Code><Message>Your proposed upload exceeds the maximum allowed size</Message><ProposedSize>52432788</ProposedSize><MaxSizeAllowed>52428800</MaxSizeAllowed><RequestId>N8RFYCS0K10GB4FF</RequestId><HostId>2OaG69rf19DMxItXx8J//rscZuSbxU8hJ/93du/a1zaFwAZa6jN2v1xCDebW4MRMgW3Kfuw0n10=</HostId></Error>
But Axios:
does not return it, just returns a generic error message: Request failed with status code 400"
and also breaks when trying to parse it.
This is the code I am running for the upload to S3:
let dataForm = new FormData();
dataForm.append('key', functionParams.uploadData.fields.key);
dataForm.append('bucket', functionParams.uploadData.fields.bucket);
dataForm.append('X-Amz-Algorithm', functionParams.uploadData.fields['X-Amz-Algorithm']);
dataForm.append('X-Amz-Credential', functionParams.uploadData.fields['X-Amz-Credential']);
dataForm.append('X-Amz-Date', functionParams.uploadData.fields['X-Amz-Date']);
dataForm.append('Policy', functionParams.uploadData.fields.Policy);
dataForm.append('X-Amz-Signature', functionParams.uploadData.fields['X-Amz-Signature']);
dataForm.append('file', fs.createReadStream(functionParams.assetFullPath),
{ knownLength: fs.statSync(functionParams.assetFullPath).size }
);
const uploadServiceURL = uploadData.url;
var config = {
method: 'POST',
url: uploadServiceURL,
headers: {
...dataForm.getHeaders(),
'content-length': dataForm.getLengthSync()
},
data: dataForm,
maxContentLength: Infinity,
maxBodyLength: Infinity,
transitional: {
forcedJSONParsing: false,
silentJSONParsing: false,
clarifyTimeoutError: true
}
};
axios(config)
.then(answer => {
resolve(answer);
})
.catch((error) => {
console.log(`Error:`)
console.log(error.toJSON())
reject(error)
})
This is the error I get from Axios:
{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/Users/vlad/modules/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/Users/vlad/modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/Users/vlad/modules/node_modules/axios/lib/adapters/http.js:322:11)\n at IncomingMessage.emit (events.js:412:35)\n at endReadableNT (internal/streams/readable.js:1317:12)\n at processTicksAndRejections (internal/process/task_queues.js:82:21)",
"config": {
"transitional": {
"silentJSONParsing": false,
"forcedJSONParsing": false,
"clarifyTimeoutError": true
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": null,
"maxBodyLength": null,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "multipart/form-data; boundary=--------------------------913873697821807580301477",
"content-length": 114310407,
"User-Agent": "axios/0.26.0"
},
"method": "post",
"url": "https://s3.us-east-1.amazonaws.com/public-assets.bluescape.com",
"data": {
"_overheadLength": 938,
"_valueLength": 114309413,
"_valuesToMeasure": [],
"writable": false,
"readable": true,
"dataSize": 0,
"maxDataSize": 2097152,
"pauseStreams": true,
"_released": true,
"_streams": [],
"_currentStream": null,
"_insideLoop": false,
"_pendingNext": false,
"_boundary": "--------------------------913873697821807580301477",
"_events": {},
"_eventsCount": 1
},
"axios-retry": {
"retryCount": 0,
"lastRequestTime": 1648080399442
}
},
"status": 400
}
Any idea how can I get back the XML from S3 describing the issue?
I want to present it as the cause of the error.
I have tried using “transformResponse“ to transform the response from remote server, but I cannot make it work and accept a new error message:
var config = {
method: 'POST',
url: uploadServiceURL,
headers: {
...dataForm.getHeaders(),
'content-length': dataForm.getLengthSync()
},
data: dataForm,
maxContentLength: Infinity,
maxBodyLength: Infinity,
transformResponse: [(response, headers) => {
var resp = response;
// Note: A successful upload to S3 will return an empty response, status code 204
if (response) {
console.log(` ---> response for ${functionParams.assetFullPath} : ${JSON.stringify(response, null, ' ')} `)
var resp;
try {
// Detect an error when parsing the answer: XML or something else
resp = JSON.parse(response)
console.log(`==> answer parsed:`)
console.log(JSON.stringify(resp, null, ' '))
} catch (error) {
console.log(` ===> ERROR parsing response for ${functionParams.assetFullPath}: ${JSON.stringify(error, null, ' ')}`)
// Trying to construct an XML response
resp = {
"test message": "manually created error message"
}
}
}
console.log(`----> Response to send back: ${JSON.stringify(resp, null, ' ')}`)
return resp;
}, ...axios.defaults.transformRequest],
transitional: {
forcedJSONParsing: false,
silentJSONParsing: false,
clarifyTimeoutError: true
}
};

Axios cannot automatically parse XML. You can get the response as a string if you use the text response type.
config = {...config, responseType: 'text'}
Then, the response will be included in answer.data as a string. Of course, if you need to do anything smarter than just printing the response, you'll still need to parse it by using the DOMParser, for example.

Related

invalid json response body at http://localhost:8080/auth/admin/realms/RealmName/users reason: Unexpected end of JSON input

user.js:(In keycloak_add_user, i need to get proper response id of the user added in the keycloak. But user is successfully added, but getting this response, so not able to assign role for the user. Please help if any changes required for my code?)
const payload = {
email: req.payload.email,
firstName: req.payload.first_name,
lastName: req.payload.last_name,
credentials: [
{
type: 'password',
temporary: false,
value: req.payload.password,
},
],
enabled: true,
emailVerified: true,
createdTimestamp: Date.now(),
requiredActions: ['UPDATE_PASSWORD'],
};
const token = req.headers.authorization;
const keycloak_add_user = await fetch(
`http://${process.env.KEYCLOAK_HOST}:${process.env.KEYCLOAK_PORT}/auth/admin/realms/${process.env.REALM_NAME}/users`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: token,
},
body: JSON.stringify(payload),
}
);
console.log('keycloak_add_user',keycloak_add_user)
if (keycloak_add_user.status !== 201 || !keycloak_add_user) {
return h
.response({ error: keycloak_add_user.statusText })
.code(keycloak_add_user.status);
}
const keycloak_user = await keycloak_add_user.json();
console.log('keycloak_user', keycloak_user)
response:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'http://13.213.9.103:8080/auth/admin/realms/Rubick/users',
status: 201,
statusText: 'Created',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
You need to call a new user GET call after adding user.
The adding user POST call did not response a new user's id. it returned just 201 Created status.
This node java script is example to get new user id.
import fetch from "node-fetch";
const displayUserId = async () => {
const token ='eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICI5VXBWcTVsQ3Ywc2FZRGNCMHNpOWNscjB2Nmk5aGRPeXAtaS1XQk1ydXJFIn0.eyJleHAiOjE2NTU0Mzc0ODAsImlhdCI6MTY1NTQwMTQ4MCwianRpIjoiOGRjNjM0YjMtNjg4Zi00NWIzLWE5ODItYWVhZDFkNGFiNTU2IiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MTgwL2F1dGgvcmVhbG1zL3Rlc3QiLCJzdWIiOiI2OTFiMWNkNC1lMzZjLTQ5ZDktOTQ0Zi0yZGZjNjI5MWNlOTciLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZG1pbi1jbGkiLCJzZXNzaW9uX3N0YXRlIjoiYWU2OTBiNjAtMTY5OS00NjAwLThmNDItMTc1NzNiZDllMzUwIiwiYWNyIjoiMSIsInNjb3BlIjoicHJvZmlsZSBlbWFpbCIsInNpZCI6ImFlNjkwYjYwLTE2OTktNDYwMC04ZjQyLTE3NTczYmQ5ZTM1MCIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwibmFtZSI6IkZpcnN0TmFtZSBMYXN0TmFtZSIsInByZWZlcnJlZF91c2VybmFtZSI6InVzZXIxIiwiZ2l2ZW5fbmFtZSI6IkZpcnN0TmFtZSIsImZhbWlseV9uYW1lIjoiTGFzdE5hbWUiLCJlbWFpbCI6InVzZXIxQHRlc3QuY29tIn0.bCbAgp3uvbQNCWSXWBX00QJl_zSZmspn0o2Jfejrznlf8ocYxcyWEVG4Cg_aEfqNn0lrdfhllftsZTTJlxrE4F19xg9GSdoya-DsY_fhwvtQZ-gHkxbLwjMqa06eSHxUCxhtk0FNjToxnv_5LSic3z09K9BRi5QXG9peMq_BoLpOjwfbROJHEDvByPtwZpxib6iWeXUl1S8ZwMaW3lJ6bqisbd2GVMJqaVMm0zp9tXws_LOP5lTCWuRKXXWJC0V3Oubd-qN_wQoNw9_R9CNlcVkIrJ3MbZqnEbdczU8-eX5lLnydjVa1eKzo6Rfnh4387vyai80kFPUN2mb4x20xOw';
const got = await fetch('http://localhost:8080/auth/admin/realms/test/users/?username=newmyuser',
{
method: 'GET',
headers: {
'Content-Type' : 'application/json',
Authorization: 'Bearer ' + token
}
}
);
const response = await got.json();
console.log(response);
console.log(response.map(({ id }) => ({ id })))
}
displayUserId();
And it's display a response in terminal.
$ node get-api.js
[
{
id: '70fb1f9f-257d-4f11-8e3d-b0e01bafa47f',
createdTimestamp: 1655395295332,
username: 'newmyuser',
enabled: true,
totp: false,
emailVerified: false,
firstName: 'newFirstName',
lastName: 'newLastName',
email: 'newtestuser#test.com',
disableableCredentialTypes: [],
requiredActions: [],
notBefore: 0,
access: {
manageGroupMembership: true,
view: true,
mapRoles: true,
impersonate: false,
manage: true
}
}
]
[ { id: '70fb1f9f-257d-4f11-8e3d-b0e01bafa47f' } ]
There is no response body, so "invalid json response body" is correct = don't expect JSON response body. There is the Location header (with user id parameter), which is just telling you where you can find the resource.
So if you need user id, then parse Location header or you can pass id in the request payload and Keycloak will use it (or it will return an error if that id is already used).

AWS S3 file upload Get 400 error code while file upload- Pinterest API

I want to create a pin with Pinterest API, So I followed official docs.
So I created a post request with this code snippet:
const options = {
method: 'POST',
url: 'https://pinterest-media-upload.s3-accelerate.amazonaws.com/',
headers: {},
formData: params,
file: {
value: fs.createReadStream(file.location),
options: {
filename: file.name,
},
},
}
request(options, function (error, response) {
if (error) throw new Error(error)
console.log(response)
console.log(response.statusCode)
})
Btw, my options output like that:
{
method: 'POST',
url: 'https://pinterest-media-upload.s3-accelerate.amazonaws.com/',
headers: {},
formData: {
'x-amz-date': '20220214T010341Z',
'x-amz-signature': '784024caf758eae76b1bfb3f61e31aa6ffaed6882867450c6d777ef5f09defa0',
'x-amz-security-token': 'IQoJb3JpZ2luX2VjEDkaCXVzLWVhc3QtMSJGMEQCIHqkv3HIUURvLPoVv0MBWxUJg8MrB1GTCmpV689cxDewAiAm/8wphXobyHdvSt5XCzB/MVyaf903CTS0BOCMPIk7BiqDBAiC//////////8BEAAaDDk5ODEzMTAzMjk5MCIMmzJXhv+p3w3LzPTpKtcDpGZmPmf4j2GTnYm1Pz/fzOlXX91H7Hjpnd5jqYGLkT4agyHNb/QLpP/0CZUogv1k7cOnjoxGRO7pqtIvshN7CTFyrvdNLkiuGLdKK52atlRzV3wWv+Mz7gmnp09YN0+hufKQ94ueJ5dueigU6Cf7rMvKVxQA+61II4GHj4WFl2dpFv2VLGsHZecg7cDvBITp13QL53z1aWojZjVGdg+0on5LGHYq8qExYQ3oy4gAq6wDTtzIBGKElOTXZYJjgLsX7ilARtm2i/Jv3MFTpCZFsoaqzCqHwsMfcIUbyCR6PKadriDU1qzYvBfUln4KItFvRxOPJ7SkOdOBcfoIq9OY7FRL8atlNh8omY9z+JD2yk8nUF69VmXjhtNjvUMQSLPzjGanHgeuwGfJwbKcc30lNopuw8cBzWbGQDFl69wPNbO0qXKjR9bW9MoPZzhl1eFVbmQ97u5pb5JnSK3/YExJTe/gQ4OgI21/TAWveNv1+j/mzPmE1rQbZ36Hfn2NP0QKulkh8TsnYDQo9Baf0mQoBqdU+WI1eeIPUu4++9viWsgmVMX1hCp8QRBPwgn+DE+lhvAx1roewoxkQGj6JXOv3koaV/f+VDI2tcjTzZ7Vr5ltsh1dyk+4MPnJppAGOqYBoK8YoVFKCclHc408UkZvQtTS4Y6TWmAhOHFpCw2dSON1hjzUQVFDXbDQ2z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HdMK09UdFJUMW5CalAzYTlNNnBaOGM2OU9aVkZKM2ZSQT09In1dfQ==',
'x-amz-credential': 'ASIA6QZJ64OPDEAU3F4A/20220214/us-east-1/s3/aws4_request',
'Content-Type': 'multipart/form-data'
},
file: {
value: ReadStream {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 1,
_maxListeners: undefined,
path: '/Users/akasaa101/Desktop/vas-project/social-service/temp/VIIcz8eR6y.mp4',
fd: null,
flags: 'r',
mode: 438,
start: undefined,
end: Infinity,
autoClose: true,
pos: undefined,
bytesRead: 0,
closed: false,
[Symbol(kFs)]: [Object],
[Symbol(kCapture)]: false,
[Symbol(kIsPerformingIO)]: false
},
options: { filename: 'VIIcz8eR6y.mp4' }
}
}
But I get an error as :
'<Error><Code>InvalidArgument</Code><Message>POST requires exactly one file upload per request.</Message><ArgumentName>file</ArgumentName><ArgumentValue>0</ArgumentValue><RequestId>VZ5RH6P8MD14E6CP</RequestId><HostId>loa5iyjv2L3yRHhK0nsu4pIa1VqmvKn9nxgRs2euKlUaZ2mS5Emb0KUGolNeKDu3upY2VPxN8Zo=</HostId></Error>',
By the way, I tried to send the same request with axios but I get a different error.
But now I get an error as "POST requires exactly one file upload per request.".
I checked my options but I cannot find any error on my code snipped.
How can I solve this problem? Please Help!

Home Assistant - Request failed Error code 400

I made this function to make it possible to send announcements to my google home mini but im getting error code 400 (Bad Request) nonstop. I tried using multiple approaches to this.
In Home-Assistant, i have setup my Google Home and can play media through it but whenever i try it with the "google_say" API of Home-Assistant it doesn't work.
I also tried calling the Home-Assistant API over my Phone using an App called "API Client" but i got the same response.
function ttsGoogleHome(text) {
var ttsUrl = "http://127.0.0.1:8123/api/services/tts/google_say?api_password=<MY_PASSWORD>"
var varToken = "<MY_TOKEN>"
var postData = {"entity_id": "media_player.david", "message": `${text}`};
let axiosConfig = {
headers: {
'authorization': `Bearer ${varToken}`,
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
}
};
axios.post(ttsUrl, postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", JSON.stringify(res));
})
.catch((err) => {
console.log("AXIOS ERROR: ", JSON.stringify(err));
})
}
This is the response i get in the server:
{
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n
at createError (/home/pi/nodejs/node_modules/axios/lib/core/createError.js:16:15)\n
at settle (/home/pi/nodejs/node_modules/axios/lib/core/settle.js:17:12)\n
at IncomingMessage.handleStreamEnd (/home/pi/nodejs/node_modules/axios/lib/adapters/http.js:260:11)\n
at IncomingMessage.emit (events.js:388:22)\n
at endReadableNT (internal/streams/readable.js:1336:12)\n
at processTicksAndRejections (internal/process/task_queues.js:82:21)",
"config": {
"url": "http://127.0.0.1:8123/api/services/tts/google_say?api_password=<MY_PASSWORD>",
"method": "post",
"data": "{\"entity_id\":\"media_player.david\",\"message\":\"Erste Stunde Fach Deutsch Lehrer Schemmer Raum Schemmer\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"authorization": "Bearer <MY_TOKEN>",
"Access-Control-Allow-Origin": "*",
"User-Agent": "axios/0.21.1",
"Content-Length": 103
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
}
I found my error.
I used the wrong api link
here is the correct way to call it.
function ttsGoogleHome(text) {
var ttsUrl = "http://127.0.0.1:8123/api/services/tts/google_translate_say?api_password=APIPASSWORD"
var varToken = "TOKEN"
var postData = `{"entity_id": "media_player.david", "message": "${text}", "language": "de"}`;
let axiosConfig = {
data: null,
headers: {
'authorization': `Bearer ${varToken}`,
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
}
};
axios.post(ttsUrl, postData, axiosConfig)
.then((res) => {
console.clear();
console.info("RESPONSE RECEIVED: ", JSON.stringify(res));
})
.catch((err) => {
console.clear();
console.error("AXIOS ERROR: ", JSON.stringify(err));
})
}
also here is my configuration.yaml:
# Configure a default steup of Home Assistant (frontend, api, etc)
# Text to speech
tts:
- platform: google_translate
- language: "de"
- service_name: google_say
-base_url: http://192.168.0.176:8123
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
homeassistant:
auth_providers:
- type: legacy_api_password
api_password: !secret http_password

Error when saving to Storage at Google Cloud Function: { Error: Could not refresh access token: Unsuccessful response status code...}

I've written my code some month ago, and now without changing something there is an error message and I don't know why.
My Code in a Google Cloud Function loads a picture from an AWS S3 bucket to google cloud and saves it in a bucket, which was actually working some month ago!
My code is running node.js 8:
const tmpdir = os.tmpdir();
const filePath = path.join(tmpdir, fileName);
console.log(filePath);
console.log(data);
await writeFile(filePath, data.Body);
const bucketName = "test";
console.log('test1');
let storage;
if(!storage){
storage = new Storage();
}
await storage.bucket(bucketName).upload(filePath, {
gzip: false,
metadata: {
cacheControl: "public, max-age=31536000"
}
});
console.log('test2');
console.log(`${filePath} uploaded to ${bucketName}.`);
"test1" is printed in the logs, but "test2" not.
The error I get:
function-138m28l2agh39{ Error: Could not refresh access token: Unsuccessful response status code. Request failed with status code 500
at Gaxios._request (/srv/node_modules/gaxios/build/src/gaxios.js:85:23)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:229:7)
response:
{ config:
{ url: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fiam%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.full_control',
headers: [Object],
retryConfig: [Object],
params: [Object],
responseType: 'text',
timeout: 0,
paramsSerializer: [Function: paramsSerializer],
validateStatus: [Function: validateStatus],
method: 'GET' },
data: 'Could not fetch URI /computeMetadata/v1/instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fiam%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.full_control\n',
headers:
{ connection: 'close',
'content-length': '260',
'content-type': 'text/plain; charset=utf-8',
date: 'Thu, 16 Jul 2020 14:25:37 GMT',
'x-content-type-options': 'nosniff' },
status: 500,
statusText: 'Internal Server Error',
request:
{ responseURL: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fiam%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.full_control' } },
config:
{ url: 'http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token?scopes=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fiam%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform%2Chttps%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdevstorage.full_control',
headers: { 'Metadata-Flavor': 'Google' },
retryConfig:
{ noResponseRetries: 3,
currentRetryAttempt: 3,
retry: 3,
httpMethodsToRetry: [Array],
statusCodesToRetry: [Array] },
params:
{ scopes: 'https://www.googleapis.com/auth/iam,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/devstorage.full_control' },
responseType: 'text',
timeout: 0,
paramsSerializer: [Function: paramsSerializer],
validateStatus: [Function: validateStatus],
method: 'GET' },
code: '500' }
Did somebody face a similar issue or can somebody help? :)

"RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request: reason: invalid patch for uri urlList.json: invalid path: /test/

I have a marklogic database with the following JSON document named urlList.json
{
"test": {
"ip": "10.10.10.10",
"fqdn": "www.test.test"
}
}
I am trying to add to the test object with the marklogic rest API using patch. I am using Node with the request-promise module here is the code
var options = {
method: 'PATCH',
url: 'https://test:8000/v1/documents',
qs: { database: databaseName, uri: 'urlList.json' },
headers:
{
'Content-Type': 'application/json',
Accept: 'application/json'
},
strictSSL: false,
auth: {
user: userName,
pass: password,
sendImmediately: false
},
body: JSON.stringify({
"patch": [
{
"insert": {
"context": "/test/",
"position": "last-child",
"content": { "test": "test"}
}
}
]
})
};
request(options)
.then(results => {
return resolve(results);
})
.catch(err => {
return reject(err);
})
The desired outcome when it runs is
{
"test": {
"ip": "10.10.10.10",
"fqdn": "www.test.test",
"test": "test"
}
}
I get the following error every time I run it
"400 - "{\"errorResponse\":{\"statusCode\":400, \"status\":\"Bad
Request\", \"messageCode\":\"RESTAPI-INVALIDREQ\",
\"message\":\"RESTAPI-INVALIDREQ: (err:FOER0000) Invalid request:
reason: invalid patch for uri urlList.json: invalid path: /test/\"}}""
Here is the body that is sent
"{"patch":[{"insert":{"context":"/test/","position":"last-
child","content":{"test":"test"}}}]}"
A path must select a node. For that reason, a path can't end with a separator. That's what the message attempts to convey.
Does it work with a path of /test?
By the way, MarkLogic provides a Node.js API with support for promises. That might be easier to work with.
Hoping that helps,

Resources