Why is my POST method not working in Angular - javascript

When I send data in postman , I've got 200 status - success [
But when I try to send POST request to the same URL through Angular CLI , Ive got 400 error, which says MALFORMED_JSON
const testData = {
"address_1": "ddd",
"contact_person_1": "ddd",
"full_name": "dsad",
"is_active": 2,
"phone_no_1": "11111",
}
return this.http.post(`${this.urlAdmin}branches/save`, testData).pipe(
catchError((err) => {
console.log('err' , err)
return of(false);
})
);
Here is screen below of my params in request in browser
Can somebody help please ?

You can follow this sequence when calling api from Angular:
this.http.post(baseUrl ,parameterModel, headers).pipe();
, as i see you need to add the header, your model, and make sure from the api path.

Related

Firebase messaging missing Authentication key in MongoDB trigger functions:

Please I need help. I don't know what I am doing wrong. I am trying to send push notification from http request but I keep getting this error:
The request was missing an Authentication Key. Please, refer to section "Authentication" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.
I am currently doing this:
const response = await context.http.post({
url:"https://fcm.googleapis.com/fcm/send",
header:{"Content-Type": "application/json",
"Authorization":"key= Web Server Key"},
body:{
"to": usersPushToken, // From FirebaseMessaging.instance.getToken();
"notification": {
"title": "Title",
"body": "body",
"clickAction": 'FLUTTER_NOTIFICATION_CLICK',
"sound": 'default',
},
}
},
encodeBodyAsJSON: true,
});
My web server key (Cloud Messaging API (Legacy)) I also tried API key:
This was my fault (headers not header). But I will leave this answer for anyone using Flutter, MongoDB, and Firebase Messaging.
const response = await context.http.post({
url:"https://fcm.googleapis.com/fcm/send",
"headers":{"Content-Type": ["application/json"], //Must be in array
"Authorization":["key= Web Server Key"]}, //Must be in array
"body":{
"to": usersPushToken, // From FirebaseMessaging.instance.getToken();
"notification": {
"title": "Title",
"body": "body",
"clickAction": 'FLUTTER_NOTIFICATION_CLICK',
"sound": 'default',
},
}
},
encodeBodyAsJSON: true,
});

JavaScript Jest Testing Using fetch() and getting 'Undefined' from JSON data

I am learning fetch and javascript testing using jest. I've encountered the following problem and have tried to resolve it but failed:
I am trying to validate some data from JSON from https://reqres.in/api/users/1 using JavaScript Jest testing via fetch() to fetch the data from JSON. But it returns failed as (see also screenshot attached):
expect(received).toEqual(expected) // deep equality
Expected: "George"
Received: undefined
The JSON data from https://reqres.in/api/users/1:
data:
id 1
email "george.bluth#reqres.in"
first_name "George"
last_name "Bluth"
avatar "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
Here is what I've done:
I created a user.js file which has a function called fetchData() to fetch the data from https://reqres.in/api/users/1. The fetchData() code:
function fetchData(){
return fetch('https://reqres.in/api/users/1')
.then(response => response.json());
});
I also created a user.test.js test file as:
const fetchData = require('./user');
test('Verify first name', () => {
return fetchData().then(data => {
expect(data.first_name).toEqual('George');
});
});
when I run the test (npx jest user.test.js), it returned failed and showed the result as indicated above. The test should pass as the JSON data for first name matches the expected string "George". I think the problem here is that the data that was returned by JSON somehow is incorrect and so it says undefined. How should I correct my code?
I've tried a number of ways trying to fix this error, including using JSON.stringify and JSON.parse to return the JSON data in order to compare with the expected string, but both not successful. I'm at this point not sure what I have done incorrectly. Can someone help me in pinpointing to me why it says undefine?
Your help is very much appreciated.
The response is:
{
"data": {
"id": 1,
"email": "george.bluth#reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
},
"ad": {
"company": "StatusCode Weekly",
"url": "http://statuscode.org/",
"text": "A weekly newsletter focusing on software development, infrastructure, the server, performance, and the stack end of things."
}
}
There is data key in the response, so it should be:
test('Verify first name', () => {
return fetchData().then(data => {
expect(data.data.first_name).toEqual('George');
});
});

webauthn authentication javascript formatting assistance

I have been trying to figure out how to do 2fa with webauthn and I have the registration part working. The details are really poorly documented, especially all of the encoding payloads in javascript. I am able to register a device to a user, but I am not able to authenticate with that device. For reference, I'm using these resources:
https://github.com/cedarcode/webauthn-ruby
https://www.passwordless.dev/js/mfa.register.js
And specifically, for authentication, I'm trying to mimic this js functionality:
https://www.passwordless.dev/js/mfa.register.js
In my user model, I have a webauthn_id, and several u2f devices, each of which has a public_key and a webauthn_id.
In my Rails app, I do:
options = WebAuthn::Credential.options_for_get(allow: :webauthn_id)
session[:webauthn_options] = options
In my javascript, I try to mimic the js file above and I do (this is embedded ruby):
options = <%= raw #options.as_json.to_json %>
options.challenge = WebAuthnHelpers.coerceToArrayBuffer(options.challenge);
options.allowCredentials = options.allowCredentials.map((c) => {
c.id = WebAuthnHelpers.coerceToArrayBuffer(c.id);
return c;
});
navigator.credentials.get({ "publicKey": options }).then(function (credentialInfoAssertion)
{
// send assertion response back to the server
// to proceed with the control of the credential
alert('here');
}).catch(function (err)
{
debugger
console.error(err); /* THIS IS WHERE THE ERROR IS THROWN */
});
The problem is, I cannot get past navigator.credentials.get, I get this error in the javascript console:
TypeError: CredentialsContainer.get: Element of 'allowCredentials' member of PublicKeyCredentialRequestOptions can't be converted to a dictionary
options at the time navigator.credentials.get is called looks like this:
I've tried every which way to convert my db-stored user and device variables into javascript properly encoded and parsed variables but cannot seem to get it to work. Anything obvious about what I'm doing wrong?
Thanks for any help,
Kevin
UPDATE -
Adding options json generated by the server:
"{\"challenge\":\"SSDYi4I7kRWt5wc5KjuAvgJ3dsQhjy7IPOJ0hvR5tMg\",\"timeout\":120000,\"allowCredentials\":[{\"type\":\"public-key\",\"id\":\"OUckfxGNLGGASUfGiX-1_8FzehlXh3fKvJ98tm59mVukJkKb_CGk1avnorL4sQQASVO9aGqmgn01jf629Jt0Z0SmBpDKd9sL1T5Z9loDrkLTTCIzrIRqhwPC6yrkfBFi\"},{\"type\":\"public-key\",\"id\":\"Fj5T-WPmEMTz139mY-Vo0DTfsNmjwy_mUx6jn5rUEPx-LsY51mxNYidprJ39_cHeAOieg-W12X47iJm42K0Tsixj4_Fl6KjdgYoxQtEYsNF-LPhwtoKwYsy1hZgVojp3\"}]}"
This is an example of the serialised JSON data returned by our implementation:
{
"challenge": "MQ1S8MBSU0M2kiJqJD8wnQ",
"timeout": 60000,
"rpId": "identity.acme.com",
"allowCredentials": [
{
"type": "public-key",
"id": "k5Ti8dLdko1GANsBT-_NZ5L_-8j_8TnoNOYe8mUcs4o",
"transports": [
"internal"
]
},
{
"type": "public-key",
"id": "LAqkKEO99XPCQ7fsUa3stz7K76A_mE5dQwX4S3QS6jdbI9ttSn9Hu37BA31JUGXqgyhTtskL5obe6uZxitbIfA",
"transports": [
"usb"
]
},
{
"type": "public-key",
"id": "nbN3S08Wv2GElRsW9AmK70J1INEpwIywQcOl6rp_DWLm4mcQiH96TmAXSrZRHciZBENVB9rJdE94HPHbeVjtZg",
"transports": [
"usb"
]
}
],
"userVerification": "discouraged",
"extensions": {
"txAuthSimple": "Sign in to your ACME account",
"exts": true,
"uvi": true,
"loc": true,
"uvm": true
}
}
This is parsed to an object and the code used to coerce those base64url encoded values is:
credentialRequestOptions.challenge = WebAuthnHelpers.coerceToArrayBuffer(credentialRequestOptions.challenge);
credentialRequestOptions.allowCredentials = credentialRequestOptions.allowCredentials.map((c) => {
c.id = WebAuthnHelpers.coerceToArrayBuffer(c.id);
return c;
});
Hope that helps. The JSON data is retreived via a fetch() call and the byte[] fields are encoded as base64url on the serverside.

Consume AZURE ML with nodejs error 400 status code

I have a problem when I try to consuming the web service, the error is:
The request failed with status code: 400
{"error":
{"code":"BadArgument","message":"Invalid argument provided.",
"details":[{"code":"BatchJobInputsNotSpecified","message":"The following required input(s) were not specified with the request: input1. Please ensure all input data is specified and try again."}]}}
I don't know how to solve that, because in the code I send input1.
Please help me, thanks.
let req = require("request");
const uri = "bla";
const apiKey = "key";
let data = {
"Inputs": {
"input1":
[
{
'IdEmpleado': "20000",
'NivelSatisfaccion': "0.38",
'SatisfaccionLaboral_Disc': "Insatisfecho",
'UltimaEvaluacion': "0.53",
'UltimaEvaluacion_Disc': "Media",
'ProyectosRealizados': "2",
'ProyectosRealizados_Disc': "[2-3]",
'HorasMensuales': "157",
'HorasMensuales_Disc': "[150-199]",
'Antiguedad': "3",
'Antiguedad_Disc': "[2-4]",
'AccidentesTrabajo': "0",
'AccidentesTrabajo_Disc': "NO",
'Ascendido': "0",
'Ascendido_Disc': "NO",
'AreaTrabajo': "Ventas",
'NivelSalarial': "Bajo",
'Renuncia': "1",
'Renuncia_Disc': "SI"
}
],
},
"GlobalParameters": {}
}
The scoring uri expects the body of the request to be a JSON document with the following structure:
{
"data":
[
<model-specific-data-structure>
]
}
The structure of the data needs to match what the scoring script and model in the service expect. Please follow the following document for more information.

Creating an asana task with asana api gives invalid identifier error

MY Payload looks like this.
var data={
"workspace":"1234",
"name": task_name ,
"notes":striped_msg ,
"memberships":[
{
"project":678,
"section":111
},
{
"project":1230
}
],
"custom_fields":{
"303093523672299":"303093523672300"
},
"due_on":string_date
}
sending the payload like this.
var status = await asanaService.addTask(JSON.stringify(data))
Getting the following error in response
{"errors":[{"message":"Could not interpret {\"workspace\":"1234",\"name\":\"rohit as an identifier in {\"workspace\":"1234",\"name\":\"rohit.one [ Mysql cpu ]\",\"notes\":..............","help":"For more information on API status codes and how to handle them, read the docs on errors: https://asana.com/developers/documentation/getting-started/errors"}]}
I was Missing the JSON header during post

Categories