Cannot put "body' in fetch post request - javascript

I have a problem with posting data throw REST API and fetch request. The request status is 200, and object goes to data base, but without body:( Since i use Insomnia, object only have an id and some "__v" key. Here`s result in data base
{
"_id": "5aa7c133610f563a089d9ccf",
"__v": 0
},
{
"_id": "5aa7c134610f563a089d9cd0",
"__v": 0
},
and my API function
function api(endpoint) {
endpoint = `http://localhost:3030/api/${endpoint}`;
return {
get() {
return fetch(endpoint)
},
post(body) {
return fetch(endpoint, {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'},
body: JSON.stringify(body)
});
},
delete() {
return fetch(endpoint, {
method: 'DELETE'
})
}
}
}
let obj = {
name: "Apple",
nutritional_value: 100,
proteins: 200,
fats: 120,
carbohydrates: 3215,
description: "some delicious apple",
image: "apple.png",
type: "fruit"
};
api('food').post(obj);
So, what`s the problem? Help, please:)

Related

how to deal with agora cloud recording error at stop

hello guys I am using agora cloud recording with amazon s3 but my I am getting an error when I stop the web page recording as below
fetch(`https://api.agora.io/v1/apps/${APP_ID}/cloud_recording/resourceid/${resource_id}/mode/web/start`,{
method: 'POST',
headers:{
'Content-Type': 'application/json;charset=utf-8',
'Authorization':'Basic ' + authorization
},
body: JSON.stringify({
"cname": CHANNEL,
"uid": UID.toString(),
"clientRequest": {
"token": token,
"extensionServiceConfig": {
"errorHandlePolicy": "error_abort",
"extensionServices": [
{
"serviceName": "web_recorder_service",
"errorHandlePolicy": "error_abort",
"serviceParam": {
"url": window.location,
"audioProfile": 0,
"videoWidth": 1280,
"videoHeight": 720,
"maxRecordingHour": 1,
"maxVideoDuration": 200
}
}
]
},
"recordingFileConfig": {
"avFileType": [
"hls",
"mp4"
]
},
"storageConfig": {
"vendor": 1,
"region": 3,
"bucket": BUCKET_NAME,
"accessKey": ACCESS_KEY,
"secretKey": SECRET_KEY
"fileNamePrefix": [
"media",
]
}
}
})
}).then(response => {
return response.json().then(data => {
sid = data.sid;
})
})
but I am a getting a response of 'Failed to find worker' from the server and I have properly entered my S3 bucket credentials.
Any help please

How To Send JSON Array Object POST Request Using jQuery Ajax

I need To send JSON Array Object to my back-end using ajax. I can send this data using POSTMAN But I can find out the way to send these data using ajax...I really need your help.
This is my JSON Array Object -
{
"bookingID": "B005",
"rentDate": "2021-06-15",
"returnDate": "2021-06-27",
"bookingStatus": "",
"rentStatus": "",
"custNICNumber": {
"custNICNumber": "C001",
},
"driverNICNumber": {
"driverNICNumber": "D001",
},
"bookingDetails": [{
"bookingDetailsID": "",
"lossDamage": 12000.00,
"lossDamageImage": "lossDamageImage",
"bookingID": {
"bookingID": "B005",
},
"driverNICNumber": {
"driverNICNumber": "D001",
}
},
"vehicleRegID": {
"vehicleRegID": "V001",
}
},
{
"bookingDetailsID": "",
"lossDamage": 12000.00,
"lossDamageImage": "lossDamageImage",
"bookingID": {
"bookingID": "B005",
},
"driverNICNumber": {
"driverNICNumber": "D001",
}
},
"vehicleRegID": {
"vehicleRegID": "V001",
}
}
]
}
And This Is The Method I am trying to send my data to my back-end..
$('#btnPlaceBooking').click(function() {
let bookingID = $('#txtBookingID').val();
let rentDate = $('#txtRentDate').val()
let returnData = $('#txtReturnDate').val();
let custNICNumber = $('#txtCustomerID').val();
let driverNICNumber = $('#txtDriverID').val();
console.log("AddDetails")
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_end_war_exploded/booking",
contentType: "application/json",
async: true,
data: JSON.stringify({
bookingID: bookingID,
bookingStatus: "",
rentData: rentDate,
rentStatus: "",
returnData: returnData,
custNICNumber: custNICNumber,
driverNICNumber: driverNICNumber
}),
success: function(date) {
console.log("AddDetails" + date)
}
})
})
I Really need Your Help..Thank You..!

Authentication failed due to invalid authentication credentials or a missing Authorization header. in nodejs paypal sdk

I am trying to implement paypal subscription api in react-nodejs project.i refer https://developer.paypal.com/docs/api/subscriptions/v1/. after that i got id wit "P-*********".
What i have tried is:
in Ui Side(React) i created an event for requesting server side to create the billing plans.
in server side(nodejs) i do billingPlan create and update actions.
The code is:(nodejs)
export const paypalSubscribe = async (user, data) => {
const customerId = user.customer,
{ invoice: invoiceId } = data;
try {
const billingPlanAttributes = {
description: "Create Plan for Regular",
merchant_preferences: {
auto_bill_amount: "yes",
cancel_url: "http://www.cancel.com",
initial_fail_amount_action: "continue",
max_fail_attempts: "1",
return_url: "http://www.success.com",
setup_fee: {
currency: "USD",
value: "25"
}
},
name: "Testing1-Regular1",
payment_definitions: [
{
amount: {
currency: "USD",
value: order.price.recurringAmount
},
charge_models: [
{
amount: {
currency: "USD",
value: "10.60"
},
type: "SHIPPING"
},
{
amount: {
currency: "USD",
value: "20"
},
type: "TAX"
}
],
cycles: "0",
frequency: "MONTH",
frequency_interval: order.billingCycle,
name: "Regular 1",
type: "REGULAR"
}
],
type: "INFINITE"
};
const createdBillingPlan = await new Promise((resolve, reject) => {
Paypal.billingPlan.create(billingPlanAttributes, function (
error,
billingPlan
) {
if (error) {
reject(error);
} else {
resolve(billingPlan);
}
});
});
console.log("data123....", createdBillingPlan);
// update
var billing_plan_update_attributes = [
{
op: "replace",
path: "/",
value: {
state: "ACTIVE"
}
}
];
console.log(
"billing_plan_update_attributes",
billing_plan_update_attributes
);
const updateBillingPlan = await new Promise((resolve, reject) => {
Paypal.billingPlan.update(
createdBillingPlan.id,
billing_plan_update_attributes,
function (error, response) {
if (error) {
reject(error);
} else {
resolve(response);
}
}
);
});
const getBillingPlan = await new Promise((resolve, reject) => {
Paypal.billingPlan.get(createdBillingPlan.id, function (
error,
updatedBillingPlan
) {
if (error) {
console.log("errr", error.response);
reject(error);
} else {
console.log("updatedBillingPlan", JSON.stringify(updatedBillingPlan));
resolve(updatedBillingPlan);
updatedBillingPlan.redire
}
});
});
console.log("getBillingPlan", getBillingPlan);
return { ok: true, data: getBillingPlan };
} catch (error) {
console.log("error", error);
}
};
And i got getBillingPlan is like this:
{ id: 'P-**************',
state: 'ACTIVE',
name: 'Testing1-Regular1',
description: 'Create Plan for Regular',
type: 'INFINITE',
payment_definitions:
[ { id: 'PD-0EF41434TA3045459BCMIRMA',
name: 'Regular 1',
type: 'REGULAR',
frequency: 'Month',
amount: [Object],
cycles: '0',
charge_models: [Array],
frequency_interval: '1' } ],
merchant_preferences:
{ setup_fee: { currency: 'USD', value: '25' },
max_fail_attempts: '1',
return_url: 'http://www.success.com',
cancel_url: 'http://www.cancel.com',
auto_bill_amount: 'YES',
initial_fail_amount_action: 'CONTINUE' },
create_time: '2020-07-01T04:18:01.008Z',
update_time: '2020-07-01T04:18:02.031Z',
links:
[ { href:
'https://api.sandbox.paypal.com/v1/payments/billing-plans/P-***********',
rel: 'self',
method: 'GET' } ],
httpStatusCode: 200
}
And when i trying to open the links in links array
ie,https://api.sandbox.paypal.com/v1/payments/billing-plans/P-***********' i got the error:
"Authentication failed due to invalid authentication credentials or a missing Authorization
header."
Where i went wrong? How can i resolve this and implement subscription of paypal in my Project.
REST Api
i changed my code to rest api calls finaly i got response like this:
{ status: 'APPROVAL_PENDING',
id: 'I-1FU83BNMBCFS',
create_time: '2020-07-06T09:47:02Z',
links:
[ { href:
'https://www.sandbox.paypal.com/webapps/billing/subscriptions? ba_token=BA-3D945638N1691194P',
rel: 'approve',
method: 'GET' },
{ href:
'https://api.sandbox.paypal.com/v1/billing/subscriptions/I- 1FU83BNMBCFS',
rel: 'edit',
method: 'PATCH' },
{ href:
'https://api.sandbox.paypal.com/v1/billing/subscriptions/I-1FU83BNMBCFS',
rel: 'self',
method: 'GET' } ],
responseCode: 201 }
and in my ui side i opened the approval link in new window after submitting it shows 404. Why?
code:
window.open(URL, "_blank");
UPDATE:Subscription:
const subscriptionString = {
plan_id: result.id,
start_time: "2021-11-01T00:00:00Z",
shipping_amount: {
currency_code: "USD",
value: "10.00"
},
subscriber: {
name: {
given_name: "John",
surname: "Doe"
},
email_address: "customer#example.com",
shipping_address: {
name: {
full_name: "John Doe"
},
address: {
address_line_1: "2211 N First Street",
address_line_2: "Building 17",
admin_area_2: "San Jose",
admin_area_1: "CA",
postal_code: "95131",
country_code: "US"
}
}
},
application_context: {
brand_name: "walmart",
locale: "en-US",
shipping_preference: "SET_PROVIDED_ADDRESS",
user_action: "SUBSCRIBE_NOW",
payment_method: {
payer_selected: "PAYPAL",
payee_preferred: "IMMEDIATE_PAYMENT_REQUIRED"
},
return_url: "https://example.com/returnUrl",
cancel_url: "https://example.com/cancelUrl"
}
},
options = {
url: "https://api.sandbox.paypal.com/v1/billing/subscriptions",
method: "POST",
headers: headers,
body: JSON.stringify(subscriptionString)
},
activateResult = await payment.callPayaplApi(options);
return {
ok: true,
data: activateResult
};
}
There is no SDK for a Subscriptions API integration, you need to implement direct REST API calls.
The PayPal-Node-SDK never supported the Subscriptions API, only the previous billing APIs which are not compatible. Also, the PayPal-Node-SDK is no longer maintained.
You particular authentication error is due to something else, but due to the above issues it is not worth troubleshooting.
Start over and integrate correctly with direct REST API calls.

Elasticsearch JS - Variable [x] is not defined

In a test Elasticsearch index, I have indexed a document, and I now want to update the document by setting its length property to 100. I want to do this through scripting (as this is a simplified example to illustrate my problem) via the elasticsearch package.
client.update({
index: 'test',
type: 'object',
id: '1',
body: {
script: 'ctx._source.length = length',
params: { length: 100 }
}
})
However, I receive the following error:
{
"error": {
"root_cause": [
{
"type": "remote_transport_exception",
"reason": "[6pAE96Q][127.0.0.1:9300][indices:data/write/update[s]]"
}
],
"type": "illegal_argument_exception",
"reason": "failed to execute script",
"caused_by": {
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"ctx._source.length = length",
" ^---- HERE"
],
"script": "ctx._source.length = length",
"lang": "painless",
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Variable [length]is not defined."
}
}
},
"status": 400
}
This happens even though I have included the length property in body.params.length.
Using the following:
Elasticsearch server v6.1.1
Elasticsearch JavaScript client v14.1.0
How can I resolve this issue?
The documentation is wrong at https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-update
In their example, they put:
client.update({
index: 'myindex',
type: 'mytype',
id: '1',
body: {
script: 'ctx._source.tags += tag',
params: { tag: 'some new tag' }
}
}, function (error, response) {
// ...
});
Whilst in fact, body.script should read:
client.update({
index: 'myindex',
type: 'mytype',
id: '1',
body: {
script: {
lang: 'painless',
source: 'ctx._source.tags += params.tag',
params: { tag: 'some new tag' }
}
}
}, function (error, response) {
// ...
});
Therefore, if you change your script to:
script: {
lang: 'painless',
source: 'ctx._source.length = params.length',
params: { length: 100 }
}
it should work!
You may want to reference the Painless Examples - Updating Fields with Painless page!

Ionic V1 $http post json data params

I have 2 objects generated by sqlite execution:
var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}
var participantes = [
{id: "10",
nome: "Antonio",
idade: "4",
ativo: 1,
msg: "Backorder"
},
{id: "11",
nome: "Carlos",
idade: "1",
ativo: 1,
msg: "Flagged"
}
]
For send the object I use this method on service:
var headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
return $http({
method: "POST",
url: "remote_url.com/action",
data: {info_update: info_update, participantes: participantes},
headers : headers
})
What's the problem?
The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image
I need send ALL data for serve.
How i do it?
Your participantes is not object its array try changing it to object using .map function

Categories