firestore is rejecting post request from angularjs - angularjs

i'm trying to add a new document to the collection Offers by using $http.post method in angularjs.
i'm getting this error in the console:
Possibly unhandled rejection: {
"data": {
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unexpected token.\nfields%5BcompanyName\n^",
"status": "INVALID_ARGUMENT"
}
},
"status": 400,
"config": {
"method": "POST",
"transformRequest": [null],
"transformResponse": [null],
"jsonpCallbackParam": "callback",
"url": "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers",
"data": "fields%5BcompanyName%5D=qwe&fields%5Bdescription%5D=qwe&fields%5BexpiredDate%5D=qwe&fields%5Btitle%5D=qwe&fields%5BuserId%5D=rsVWKar7UTMwUmcyYJbr6Rif4NN2",
"headers": {
"Content-Type": "application/json; charset=UTF-8;",
"Accept": "application/json, text/plain, /"
}
},
"statusText": "",
"xhrStatus": "complete"
}
i have tried so many solutions but none worked.
here's the controller code:
app.controller('insert_controller', function ($scope, $http, $httpParamSerializerJQLike) {
let userId = "rsVWKar7UTMwUmcyYJbr6Rif4NN2";
let url = "https://firestore.googleapis.com/v1beta1/projects/syrian-sales-v2/databases/(default)/documents/Offers";
$scope.insertOffer = function () {
let companyName = $scope.companyName;
let title = $scope.title;
let expiredDate = $scope.expiredDate;
let description = $scope.description;
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
$http({
method: 'POST',
url: url,
data: $httpParamSerializerJQLike(data),
headers: {
'Content-Type': 'application/json; charset=UTF-8;'
}
}).then(function (res) {
if (res.data){
$scope.companyName = null;
$scope.title = null;
$scope.expiredDate = null;
$scope.description = null;
alert('Offer Added Successfully')
}
}).catch(function (err) {
console.log(err);
throw err
});
}
});
any help would be great, thanks in advance
EDIT: i tried sending a post request from postman and it worked to the same url and the same json data structure i'm using

the problem was that I was using a wrong schema.
This is the old schema:
let data = {
"fields": {
"companyName": companyName,
"title": title,
"expiredDate": expiredDate,
"description": description,
"userId": userId,
}
};
This is the correct schema which worked:
let data = {
"fields": {
"companyName": {
"stringValue": companyName
},
"title": {
"stringValue": title
},
"expiredDate": {
"stringValue": expiredDate
},
"description": {
"stringValue": description
},
"userId": {
"stringValue": userId
},
}
};

Related

Invalid form with tag_field_missing when uploading a file to Discord via Discord api

I am trying to upload png_buffers stored in a variable png to discord as response to user command. It will include files[0] with that buffer and reference the attachment file in an embed. But I am not able to bypass a type required error. Any suggestion will help, thanks in advance.
Documentation: https://discord.com/developers/docs/reference#uploading-files
Code:
const formData = new FormData();
const payload = {
"type": 4,
"data":{
"content": "Hello, World!",
"embeds": [{
"title": "Hello, Embed!",
"description": "This is an embedded message.",
"thumbnail": {
"url": "attachment://test.png"
}
}],
"attachments": [{
"id": 0,
"description": "Image of a cute little cat",
"filename": "test.png"
}]
}
}
formData.append('files1', png, 'test.png');
formData.append("payload_json", JSON.stringify(payload));
const fecth_disc_api= await fetch(`https://discord.com/api/v8/interactions/${message.id}/${message.token}/callback`, {
method: 'post',
body: formData,
headers: { 'Content-Type': 'multipart/form-data' }
});
const response = await fecth_disc_api.json();
Error:
{
"code": 50035,
"errors": {
"_errors": [
{
"code": "TAG_FIELD_MISSING",
"message": "Field \"type\" is required to determine the model type."
}
]
},
"message": "Invalid Form Body"
}

Axios send strange array to React

I geting the data back from my API in React from a post request and I get just the first object of the entire Array.prototype
My API for the upload:
router.post("/uploads", upload.any(), async (req, res) => {
try {
if (!req.files) {
res.send({
status: false,
message: "No file uploaded",
});
} else {
let data = req.files;
res.send({
status: true,
message: "Files are uploaded",
data: data,
});
}
} catch (error) {
res.status(500).send(err);
}
});
POSTMAN gives me back:
{
"status": true,
"message": "Files are uploaded",
"data": [
{
"fieldname": "uploads\n",
"originalname": "46335256.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "46335256-2020-08-04.jpg",
"path": "client/uploads/46335256-2020-08-04.jpg",
"size": 19379
},
{
"fieldname": "uploads\n",
"originalname": "120360358.jpg",
"encoding": "7bit",
"mimetype": "image/jpeg",
"destination": "client/uploads/",
"filename": "120360358-2020-08-04.jpg",
"path": "client/uploads/120360358-2020-08-04.jpg",
"size": 78075
}
]
}
perfect!
this is my function in React to upload
const uploadFiles = () => {
uploadModalRef.current.style.display = "block"
uploadRef.current.innerHTML = "File(s) Uploading..."
for (let i = 0; i < validFiles.length; i++) {
const formData = new FormData()
formData.append("images", validFiles[i])
axios
.post("http://localhost:5000/api/db/uploads", formData, {
onUploadProgress: progressEvent => {
const uploadPercentage = Math.floor(
(progressEvent.loaded / progressEvent.total) * 100
)
...// code for graphic upload
},
})
.then(resp => {
console.log(resp.data.data)
resp.data.data.map(item => {
console.log(item)
})
})
.catch(() => {
... // code
}
}
and with this I get (from the console):
[{…}]
0:
destination: "client/uploads/"
encoding: "7bit"
fieldname: "images"
filename: "46335256-2020-08-04.jpg"
mimetype: "image/jpeg"
originalname: "46335256.jpg"
path: "client/uploads/46335256-2020-08-04.jpg"
size: 19379
__proto__: Object
length: 1
__proto__: Array(0)
is an array(if I map it works) but with just the first object.
How is it possible ??
I tried even with async/await but nothing changes
Where I'm mistaking?
Thanks!

How to Read the value of below json in controller.js. As i have to set the value in controller.js only

Let Me know how to access the value of response by looking to the below json data
Login Controller
app.controller('loginController', function($scope,$http, $location,
$rootScope,$window) {
$scope.submit = function(){
$rootScope.userName=$scope.username;
var username=$scope.username;
var password=$scope.password;
$http({
method: 'POST',
url: 'http://localhost:8082/APIGateway/APILoginService/login',
data: jsonData,
headers : {
'Content-Type': 'application/json',
'Orgkey': 'S2lyYW5fcmFqYWdvcGFs'
}
})
.then(function successCallback(response) {
if(response.data.code=="Invalid loginId or password" || response.data.message=="Invalid loginId or password"){
$scope.errorMessage = 'Invalid LoginId/Password';
} else {
$rootScope.loggedIn=true;
$rootScope.userName = response.data.APIUserData;
$rootScope.roleName=response.data.roleName;
}
},
};
});
This is The json data.
{
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
}
I am facing problem because of APIUserData. If i remove it i can easily access the value. can anybody help me in fixing the issue
APIUserData is an array. You could do something like this:
var myResponse = {
"APIUserData": [
{
"userID": "deve",
"firstName": "De",
"lastName": "Singh",
"mobileNumber": "990064533",
"emailID": "xyz#gmail.com",
"roleID": 1,
"Org_Id": 1,
"status": 1
}
]
};
var roleID = myResponse.APIUserData[0].roleID;

Login with $cordovaOauth in Facebook returns null data

I am using $cordovaOauth to authenticate on an Ionic app (angular/cordova) but after settings everything on developers.facebook.com and getting the access_token I call again to get user data, but it returns an error with data=null.
Code:
$scope.facebookLogin = function() {
$cordovaOauth.facebook(FACEBOOK_ID, ["email", "public_profile"], {
redirect_uri: "http://localhost/callback"
}).then(function(result) {
var access_token = result.access_token;
//console.log(JSON.stringify(result));
$http.get("https://graph.facebook.com/v2.2/me", {
params: {
access_token: access_token,
fields: "first_name,last_name,gender,picture,locale",
format: "json"
}
}).then(function(result) {
console.log("RETURN: " + JSON.stringify(result)); // Here is where I see that JSON data
}, function(error) {
alert("Error: " + error);
});
}, function(error) {
console.log(error);
});
}
And here is the returned JSON:
{
"data": null,
"status": -1,
"config": {
"method": "GET",
"transformRequest": [null],
"transformResponse": [null],
"params": {
"access_token": "EAAS8ChUdfHEBALdJimUl5TA1sfWGZAZBv8lxlRlpcSaMhKo1NQX5JEgVuTjjpYP4agdZBZCXO0vwFJs0kLXr5CEz2h35JPZAhls9ZBVyyuwfQFlfWQkFDyGMVxsZBmGZA0s6F6XO97HpJRd7c7iZCuwEHhZAKfnMdoKerT0s5HHPW3xAZDZD",
"fields": "first_name,last_name,gender,picture,locale",
"format": "json"
},
"url": "https://graph.facebook.com/v2.2/me",
"headers": {
"Accept": "application/json"
},
"withCredentials": true
},
"statusText": ""
}
Anybody has an idea of what's wrong?

I'm getting bad request when I'm trying to build a post request on AngularJS using Swagger

I'm trying to build a POST request on AngularJS using Swagger API specification.
Below presented my post specification of Swagger:
"/api/record/": {
"post": {
"responses": {
"201": {
"description": ""
}
},
"tags": [
"api"
],
"consumes": [
"application/json"
],
"operationId": "record_create",
"parameters": [
{
"in": "body",
"schema": {
"required": [
"external_ref",
"type",
"code",
"group"
],
"type": "object",
"properties": {
"external_ref": {
"description": "",
"type": "string"
},
"type": {
"description": "",
"type": "string"
},
"code": {
"description": "",
"type": "string"
},
"group": {
"description": "",
"type": "string"
}
}
},
"name": "data"
}
]
}
}
Below presented the implementation of my post request:
return API.record_create({
body: {
external_ref: $scope.externalref,
type: $scope.type.uuid,
code: $scope.code,
group: $scope.group
}
})
.then(function(obj) {
...
})
.catch(function(err) {
...
});
The full code of AngularJS which have been generated by Swagger for the 'record_create' function is the following:
/**
*
* #method
* #name #record_create
* #param {} data -
*
*/
API.prototype.record_create = function(parameters) {
if (parameters === undefined) {
parameters = {};
}
var deferred = $q.defer();
var domain = this.domain;
var path = '/api/record/';
var body;
var queryParameters = {};
var headers = {};
var form = {};
if (this.token.isQuery) {
queryParameters[this.token.headerOrQueryName] = this.token.value;
} else if (this.token.headerOrQueryName) {
headers[this.token.headerOrQueryName] = this.token.value;
} else {
headers['Authorization'] = 'Bearer ' + this.token.value;
}
headers['Content-Type'] = ['application/json'];
if (parameters['data'] !== undefined) {
body = parameters['data'];
}
if (parameters.$queryParameters) {
Object.keys(parameters.$queryParameters)
.forEach(function(parameterName) {
var parameter = parameters.$queryParameters[parameterName];
queryParameters[parameterName] = parameter;
});
}
this.request('POST', domain + path, parameters, body, headers, queryParameters, form, deferred);
return deferred.promise;
};
Although, I added all required parameters of the body in the POST request, I'm getting a bad request (400), the response presented below:
{
"group":["This field is required."],
"type":["This field is required."],
"external_ref":["This field is required."],
"code":["This field is required."]
}
Below presented headers of post request:
headers
The only error in console is the following:
console error
Do you have any idea about how can I construct the POST request, properly, using this Swagger API specification?
The auto-generated code by Swagger had change the name of "body" parameters to "data" parameters.

Resources