Home Assistant - Request failed Error code 400 - node.js

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

Related

Strapi api not giving a response when registering user even though it was updated in the admin panel

I am using Strapi with postgres to register a new Strapi end user and I am using the following code to send a post request with the new user's credentials:
//...
try {
// encrypt the user password
const encryptedUserPassword = await bcrypt.hash(password, 10);
const response = await axios.post(
"http://localhost:1337/api/auth/local/register",
{
username,
email: email.toLowerCase(),
password: encryptedUserPassword,
}
);
} catch (err) {
console.log(err);
res.status(500).send({ message: ["Registration failed"], error: err });
}
// ...
The problem that I am facing is that whenever I send the post request, the data is being successfully updated in the Strapi admin panel and eventually in the postgres database but it is not returning a successful response and it continues to process until it throws an Axios error even though the data is updated in my Strapi admin panel.
This is the error that I received when I send the post request to register a new user:
{
"message": [
"Registration failed"
],
"error": {
"message": "Request failed with status code 400",
"name": "AxiosError",
"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": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"User-Agent": "axios/0.27.2",
"Content-Length": 130
},
"method": "post",
"url": "http://localhost:1337/api/auth/local/register",
"data": "{\"username\":\"testuser04\",\"email\":\"testuser09#email.com\",\"password\":\"$2a$10$pqeADn.WL4BqHYpTonVl2.KYqoxtuJZyvdpgc659W90zmsu4Wo2jW\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
}
I am using the recommended Strapi node version 14.19.3 with the following package.json dependencies:
"devDependencies": {},
"dependencies": {
"#strapi/strapi": "4.2.3",
"#strapi/plugin-users-permissions": "4.2.3",
"#strapi/plugin-i18n": "4.2.3",
"pg": "8.6.0"
},
Could someone please help me or give me some tips on what I am doing wrong? Thank you in advance
Well, I just resolved this problem. It turns out that just needed to set the default value for the email confirmation in the admin panel to false. Also, I needed to authorize my application to make requests directly to the API

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

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.

Amazon Sp-Api createFeedDocument, No Responding (Node.js) / And InvalidInput-contentType Error

I am trying to call the createFeedDocument operation to sp-api. But I never get a response.
Here is my signedRequest:
{
path: '/feeds/2020-09-04/documents',
method: 'POST',
host: 'sellingpartnerapi-fe.amazon.com',
region: 'us-west-2',
service: 'execute-api',
headers: {
'User-Agent': 'MyAmazonApp/1.0 (Language=JavaScript;)',
'x-amz-access-token': 'Atzasd61as689d1a1f89a189198ea1f891ad89d1e891f89ae189f189165',
Accept: 'application/json',
'Accept-Charset': 'utf-8',
Host: 'sellingpartnerapi-fe.amazon.com',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
'Content-Length': 58,
'X-Amz-Security-Token': 'Fwa***********************************************',
'X-Amz-Date': '20210404T230040Z',
Authorization: 'AWS4-HMAC-SHA256 Credential=ASIASEECTM3DHQOSTQ4M/20210404/us-west-2/execute-api/aws4_request, SignedHeaders=accept;accept-charset;content-length;content-type;host;x-amz-access-token;x-amz-date;x-amz-security-token, Signature=f***********************************************e'
},
body: '{"contentType":"text/tab-separated-values; charset=UTF-8"}'
}
And if I tried to call this operation without body it gives the error shown below:
{
"statusCode": 400,
"res": {
"errors": [
{
"code": "InvalidInput",
"message": "One or more required parameters missing",
"details": "contentType;"
}
]
}
}
Your Content-Type header should be application/json

how to i send HTTP request for sending notification in firebase?

To send a notification, you'll need to send the following HTTP request:
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: key=YOUR_SERVER_KEY
{
"notification": {
"title": "New chat message!",
"body": "There is a new message in FriendlyChat",
"icon": "/images/profile_placeholder.png",
"click_action": "http://localhost:5000"
},
"to":"YOUR_DEVICE_TOKEN"
}
how can I do this??
If you're using Node.JS, I suggest you look at the documentation for Firebase's Node.JS SDK instead of manually sending HTTP requests. There's the official documentation or this nice tutorial
If you still want to go for the plain HTTP method, you can use the request npm module
$ npm install request
then in your code :
const request = require('request');
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": ['key', yourServerKey].join('=')
},
json: {
to: clientFirebaseToken,
notification: {
title: "Notification Title",
body: "This is a neat little notification, right ?"
}
});
Edit
From their GitHub
As of Feb 11th 2020, request is fully deprecated. No new changes are
expected to land. In fact, none have landed for some time.
If you use axios
axios({
method: 'post',
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
"Content-Type": "application/json",
"Authorization": ['key', yourServerKey].join('=')
},
params: {
to: clientFirebaseToken,
notification: {
title: "Notification Title",
body: "Neat indeed !"
}
}
})
If you are using React JS/ React Native, using the Axios package it can be done very easily, the sample code is below, first, you have to register for firebase cloud messaging to get the authorization key
axios.post(
'https://fcm.googleapis.com/fcm/send',
{
data: {},
notification: {
title: "Sample text1",
body: "Sample text2",
image: "Sample text3",
},
to: '/topics/TopicName',
},
{
headers: {
Authorization:
'key=Authorization key from firebase',
},
},
)
.then(Response => {
console.log(Response.data);
});

"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