Bad request. HTTP POST to api - javascript

I'm trying to return some data from an api, however when I hit the server I receive a bad request message. I think the issue lies with my JSON Stringify, have I used this function correctly to concatenate my request body?
Output:
{ request:
{ passengers: { kind: 'qpxexpress#passengerCounts', adultCount: 1 },
slice: [ [Object] ],
saleCountry: 'GB',
ticketingCountry: 'GB',
solutions: 10 } }
Upload successful! Server responded with: {
"error": {
"errors": [
{
"domain": "global",
"reason": "badRequest",
"message": "Invalid inputs: received empty request."
}
],
"code": 400,
"message": "Invalid inputs: received empty request."
}
}
Code:
var express = require('express')
var router = express.Router()
var request = require('request')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' })
})
let flightRequest = {
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}}],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
console.log(JSON.stringify("hello" + flightRequest))
JSON.stringify(flightRequest)
console.log(flightRequest)
request.post({url:'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX', flightRequest: flightRequest}, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
module.exports = router

I think you need to post the request as follows
request({
url: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX',
method: "POST",
json: JSON.stringify(flightRequest)
}, function optionalCallback(err, httpResponse, body) { ...
or it could be
request.post({
url: 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=XXXXXXXXXXXXXXXXXXXXXXXX',
json: JSON.stringify(flightRequest)
}, ...

have I used this function correctly to concatenate my request body?
This Code
let flightRequest =
{
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [
{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}
}
],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
let flightAppend = {"appended text":"hello"}
var obj = Object.assign(flightAppend, flightRequest)
console.log(JSON.stringify(obj))
Produces This Output
{
"appended text": "hello",
"request": {
"passengers": {
"kind": "qpxexpress#passengerCounts",
"adultCount": 1
},
"slice": [
{
"kind": "qpxexpress#sliceInput",
"origin": "LHR",
"destination": "OSL",
"date": "2016-12-03",
"permittedDepartureTime": {
"kind": "qpxexpress#timeOfDayRange",
"earliestTime": "06:00",
"latestTime": "11:00"
}
}
],
"saleCountry": "GB",
"ticketingCountry": "GB",
"solutions": 10
}
}
I don't know if that's what you're looking for, or which side of the API you're on, but the output is valid JSON
As opposed to the original code which produces "hello[object Object]"

Related

Sending rich message in Dialogflow fullfilment

I am trying to create a DialogFlow chatbot setting up my fullfilment with rich message but the payload that carry it never show up.
Here is the inline code I'm using:
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion, Payload} = require('dialogflow-fulfillment');
var answers = [];
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function fallback(agent) {
agent.add(`I didn't understand FULLFILMENT`);
agent.add(`I'm sorry, can you try again? FULLFILMENT`);
}
function answer1Handler(agent){
agent.add(`Intent answer1 called`);
const answer = agent.parameters.number;
answers.push(answer);
const payload = {
"text": "Trucmuche"/*,
"attachments": []*/
};
agent.add(new Payload(agent.SLACK, payload));
/*agent.add(
new Payload(agent.SLACK, payload, {rawPayload: true, sendAsMessage: true})
);*/
}
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('answer1', answer1Handler);
agent.handleRequest(intentMap);
});
This is called when reaching "answer1" intent. It works well when my answer1Handler is only:
function answer1Handler(agent){
agent.add(`Intent answer1 called`);
}
I don't know what I missed I tried both to follow the official documentation on rich message as well as this response but none helped me create my rich responses.
However, when I add a the custom payload you can see above, it doesn't answer anymore and I get an error message in raw api response. Indeed, it wither gives an error:
{
"responseId": "49e306dc-c2a9-4667-ac67-60eb3692ce98-e15c53b8",
"queryResult": {
"queryText": "1",
"parameters": {
"number": 1
},
"allRequiredParamsPresent": true,
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 5,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"intent": {
"name": "projects/pollingagent-jnscpa/agent/intents/bea1536a-dede-4faf-ab44-2ba4f80e9c0f",
"displayName": "answer1"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 4993
},
"languageCode": "en"
},
"webhookStatus": {
"code": 4,
"message": "Webhook call failed. Error: DEADLINE_EXCEEDED."
},
"alternativeQueryResults": [
{
"queryText": "1",
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 3,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"languageCode": "en"
}
]
}
Or only gives back the first message as you can see in the raw API response:
{
"responseId": "b6bc8807-eca9-45e5-b25e-30e1b4142da7-e15c53b8",
"queryResult": {
"queryText": "1",
"parameters": {
"number": 1
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
"Intent answer1 called"
]
}
}
],
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer2",
"lifespanCount": 5,
"parameters": {
"number.original": "1",
"number": 1
}
},
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4,
"parameters": {
"number.original": "1",
"number": 1
}
}
],
"intent": {
"name": "projects/pollingagent-jnscpa/agent/intents/bea1536a-dede-4faf-ab44-2ba4f80e9c0f",
"displayName": "answer1"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 217
},
"languageCode": "en"
},
"webhookStatus": {
"message": "Webhook execution successful"
},
"alternativeQueryResults": [
{
"queryText": "1",
"outputContexts": [
{
"name": "projects/pollingagent-jnscpa/agent/sessions/b6a5e9be-dd3e-7b54-3c4f-d942de297036/contexts/await_answer1",
"lifespanCount": 4
}
],
"languageCode": "en"
}
]
}
Consequently how can I send rich message within dialogflow fullfilment?

How to get rid of validation error with paypal-rest-sdk?

I am using the paypal-rest-sdk to practice using the paypal checkout. I've set up a small test and whenever I click submit in my form I get a "localhost refused to connect" error in Chrome. I've turned off my proxy and cleared my history and cache. I've also double checked my client and secret keys from Paypal. I'm not sure what I am doing wrong. Here's my code:
app.js:
const express = require('express');
const ejs = require('ejs');
const paypal = require('paypal-rest-sdk');
paypal.configure({
'mode': 'sandbox', //sandbox or live
'client_id': 'xxxxxxxx',
'client_secret': 'xxxxxxx'
});
const app = express();
app.set('view engine', 'ejs');
app.get('/', (req, res) => res.render('index'));
// create the json obj for the transaction with the order details
app.post('/pay', (req, res) => {
const create_payment_json = {
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://localhost:3000/success",
"cancel_url": "http://localhost:3000/cancel"
},
"transactions": [{
"item_list": {
"items": [{
"name": "Red Sox Hat",
"sku": "001",
"price": "25.00",
"currency": "USD",
"quantity": 1
}]
},
"amount": {
"currency": "USD",
"total": "1.00"
},
"description": "This is the payment description."
}]
};
// pass in the object we've created and now create the actual payment
paypal.payment.create(create_payment_json, function (error, payment) {
if (error) {
console.log(error);
throw error;
} else {
console.log("Create Payment Response");
console.log(payment);
res.send('test');
}
});
});
app.listen(3000, () => console.log('Server Started'));
here is what the terminal outputs from the error:
response:
{ name: 'VALIDATION_ERROR',
details: [ [Object] ],
message: 'Invalid request - see details',
information_link: 'https://developer.paypal.com/docs/api/payments/#errors',
debug_id: 'fb61fe9c14b46',
httpStatusCode: 400 },
httpStatusCode: 400 }
I expect the message of 'test' to appear on the screen when the pay route is rendered so that I know the connection works, but so far all I've gotten is "ERR_CONNECTION_REFUSED" from Chrome. Please let me know what I am doing wrong. Thanks in advance.
Your payment JSON is missing required information.
Please see an valid payment JSON below:
{
"intent": "sale",
"payer": {
"payment_method": "paypal"
},
"redirect_urls": {
"return_url": "http://www.example.com/return_url",
"cancel_url": "http://www.example.com.br/cancel"
},
"transactions": [
{
"amount": {
"currency": "USD",
"total": "200.00",
"details": {
"shipping": "10.00",
"subtotal": "190.00"
}
},
"item_list": {
"items": [
{
"name": "Foto 1",
"currency": "USD",
"sku": "123",
"quantity": "1",
"price": "190.00"
}
]
},
"description": "Payment description"
}
]
}

API for receiving JSON via POST receives a different type than sent

I'm writing an api that gets a JSON in NODE.JS. The method of sending the data is POST.
To ease the management of requests I'm using lib Express and BodyParser to interpret the body of POST requests.
I'm grouping information into a javascript object like this:
const data = {
"plan": "312409959F9FDDE444959F9C950201D7",
"sender": {
"name": $("[name=pname]").val(),
"email": $("[name=pemail]").val(),
"hash": credentials.hash,
"phone": {
"areaCode": $("[name=pphone]").val().substring(0, 2),
"number": $("[name=pphone]").val().substring(2, 11)
},
"address": {
"street": $("[name=paddress]").val(),
"number": $("[name=pnumber]").val(),
"complement": $("[name=pcomplement]").val(),
"district": $("[name=pbairro]").val(),
"city": $("[name=pcity]").val(),
"state": $("[name=puf]").val(),
"country": "BRA",
"postalCode": $("[name=pcep]").val()
},
"documents": [{
"type": "CPF",
"value": $("[name=pcpf]").val()
}]
},
"paymentMethod": {
"type": "CREDITCARD",
"creditCard": {
"token": credentials.token,
"holder": {
"name": $("[name=pownername]").val(),
"birthDate": $("[name=pbirthday]").val().split('-').reverse().join('/'),
"documents": [{
"type": "CPF",
"value": $("[name=pcpf2]").val()
}],
"phone": {
"areaCode": $("[name=pphone2]").val().substring(0, 2),
"number": $("[name=pphone2]").val().substring(2, 11)
}
},
}
}
}
The request is sent as follows:
$.post('/adherence', data, function (msg) {
console.log(msg)
})
And the receipt on my backend is like this:
app.post('/adherence', (req, res) => {
try {
console.log(req.body);
res.send("OK");
} catch (e) {
console.log(e);
res.send(e);
}
});
But what I get in req.body is this:
{ plan: '312409959F9FDDE444959F9C950201D7',
'sender[name]': 'FRancisco',
'sender[email]': 'falisson.sv#sandbox.pagseguro.com.br',
'sender[hash]': 'ceedf0fd2ffd35f4054104d305088e19e8ca9333bbf70be10bd2ea6f94af226a',
'sender[phone][areaCode]': '63',
'sender[phone][number]': '991047876',
'sender[address][street]': '1105 sul qi 3 al 3 lt 1',
'sender[address][number]': '1',
'sender[address][complement]': '',
'sender[address][district]': 'centro',
'sender[address][city]': 'palmas',
'sender[address][state]': 'TO',
'sender[address][country]': 'BRA',
'sender[address][postalCode]': 'CEP',
'sender[documents][0][type]': 'CPF',
'sender[documents][0][value]': 'CPF',
'paymentMethod[type]': 'CREDITCARD',
'paymentMethod[creditCard][token]': 'b2f303ba63964404b6c466323deb9078',
'paymentMethod[creditCard][holder][name]': 'LUCINEIA',
'paymentMethod[creditCard][holder][birthDate]': '11/01/1990',
'paymentMethod[creditCard][holder][documents][0][type]': 'CPF',
'paymentMethod[creditCard][holder][documents][0][value]': 'CPF',
'paymentMethod[creditCard][holder][phone][areaCode]': '63',
'paymentMethod[creditCard][holder][phone][number]': '991047876' }
In my opinion, everything is normal, and it was for me to be receiving the JSON in the format sent. What's wrong with my code?
Try sending your request like that:
$.ajax({
url: '/adherence',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
console.log(msg)
})
});

Angularjs $http is unable to get data from Asp.net webapi 4

I am trying to build an application with Asp.net web api and Angularjs
I am trying to get data from API but I am getting a null error as a result.
Asp.net web api code
[RoutePrefix("api/user")]
public class UserController : ApiController
{
[Route("login")]
[HttpGet]
public HttpResponseMessage login(string userId, string password)
{
...code to fetch data
return Request.CreateResponse(HttpStatusCode.OK, result);
}
web config
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
Angular Js Code
this.get = function (url, headers = {}) {
/// creating a defer
var def = $q.defer();
$http({
url: url,
dataType: 'json',
method: 'GET',
data: '',
headers: headers
}).success(function (data) {
def.resolve(data);
}).error(function (error) {
def.reject(error);
});
return def.promise;
};
Result
When I am trying to get the result by hitting the API URl I am getting error null
If I am opening the url in web browser then it is returning the JSON
Network Log
{
"log": {
"version": "1.2",
"creator": {
"name": "WebInspector",
"version": "537.36"
},
"pages": [],
"entries": [
{
"startedDateTime": "2016-06-02T16:27:59.550Z",
"time": 25.981999933719635,
"request": {
"method": "GET",
"url": "http://localhost:62158/api/user/login?userId=undefined&password=abc",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Origin",
"value": "http://localhost:8000"
},
{
"name": "Accept-Encoding",
"value": "gzip, deflate, sdch"
},
{
"name": "Host",
"value": "localhost:62158"
},
{
"name": "Accept-Language",
"value": "en-US,en;q=0.8,hi;q=0.6,und;q=0.4"
},
{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36"
},
{
"name": "Accept",
"value": "application/json, text/plain, */*"
},
{
"name": "Referer",
"value": "http://localhost:8000/"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [
{
"name": "userId",
"value": "undefined"
},
{
"name": "password",
"value": "abc"
}
],
"cookies": [],
"headersSize": 429,
"bodySize": 0
},
"response": {
"status": 200,
"statusText": "OK",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Pragma",
"value": "no-cache"
},
{
"name": "Date",
"value": "Thu, 02 Jun 2016 16:27:59 GMT"
},
{
"name": "Server",
"value": "Microsoft-IIS/8.0"
},
{
"name": "X-AspNet-Version",
"value": "4.0.30319"
},
{
"name": "X-Powered-By",
"value": "ASP.NET"
},
{
"name": "Content-Type",
"value": "application/json; charset=utf-8"
},
{
"name": "Cache-Control",
"value": "no-cache"
},
{
"name": "X-SourceFiles",
"value": "=?UTF-8?B?QzpcVXNlcnNca2lyXERlc2t0b3BcRSBEcml2ZVxXb3JrIExpdmVcTml0aW4gS0sgU29mdHdhcmVcVmlkZW9MaWJyYXJ5XHByb2plY3RcVmlkZW9MSWJyYXJ5XFZpZGVvTElicmFyeVxhcGlcdXNlclxsb2dpbg==?="
},
{
"name": "Content-Length",
"value": "46"
},
{
"name": "Expires",
"value": "-1"
}
],
"cookies": [],
"content": {
"size": 0,
"mimeType": "application/json",
"compression": 447,
"text": ""
},
"redirectURL": "",
"headersSize": 447,
"bodySize": -447,
"_transferSize": 0,
"_error": ""
},
"cache": {},
"timings": {
"blocked": 2.24999990314245,
"dns": -1,
"connect": -1,
"send": 0.19500008784235012,
"wait": 22.8659999556839,
"receive": 0.6709999870509336,
"ssl": -1
},
"serverIPAddress": "[::1]",
"connection": "15008"
}
]
}
}
Same Hit in browser giving result
As KKKKKKKK and rick have already pointed out you don't need to create another promise as $http.get will already return one. You should also make use of then as opposed to succcess/failure
So what you want should look like this:
function getData() {
return $http.get('path-to-api/api.json').then(
function success(result) {
// Do stuff with it
return result.data;
},
function failure(err) {
return err;
});
}
Note this places the call in a service and returns the function in an object from that service.
EDIT
Because the comments concates URLS I'll add this as an edit:
So the url you're hitting on the angular side is:
http://localhost:62158/api/user/login?userId=undefined&password=abc.json
or is http://localhost:62158/api/user/login?userId=undefined&password=abc
#Katana24 I do not know how to thank you but you made me get this answer... thanks a lot.
Reason
Asp.net web api does not allow cross origin request until and unless you add Access-Control-Allow-Origin in web.config file. I made it * so from any origin the APIes is accessible.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>

I update the same video ID, but the youtube-api v3 still show "Video not found"

I used google js api Link1and youtube v3 api Link2
I want use js to update my video, the js code for listing videos:
var requestOptions = {
playlistId: playlistId,
part: 'snippet',
//id: ['uY3InyzU79U','nOoHrAR50f8'],
myRating:'like',
maxResults: 9
};
if (pageToken) {
requestOptions.pageToken = pageToken;
pToken=pageToken;
}
var request = gapi.client.youtube.videos.list(requestOptions);
request.execute(somefunction());
The json response:
[
{
"id": "gapiRpc",
"result": {
"kind": "youtube#videoListResponse",
"etag": "\"Wes3wj_Yozi4a9GfHnpc8qG73KI/8qQBat1N6baCDG6C3Eed_XV_sZo\"",
"pageInfo": {
"totalResults": 3,
"resultsPerPage": 9
},
"items": [
{
"id": "nOoHrAR50f8",
"kind": "youtube#video",
"etag": "\"Wes3wj_Yozi4a9GfHnpc8qG73KI/f7JZaoHeZG-CDYzXVRw2Q11Lins\"",
"snippet": {
"publishedAt": "2013-05-30T05:37:50.000Z",
"channelId": "UCx0RClYCMhtsOXRlSyRcuRA",
"title": "Webcam video from May 30, 2013 3:36 PM",
"description": "",
"thumbnails": {
"default": {
"url": "https://i3.ytimg.com/vi/nOoHrAR50f8/default.jpg"
},
"medium": {
"url": "https://i3.ytimg.com/vi/nOoHrAR50f8/mqdefault.jpg"
},
"high": {
"url": "https://i3.ytimg.com/vi/nOoHrAR50f8/hqdefault.jpg"
},
"standard": {
"url": "https://i3.ytimg.com/vi/nOoHrAR50f8/sddefault.jpg"
}
},
"channelTitle": "foretribe1",
"tags": [
"test",
"webcam"
],
"categoryId": "22"
}
}
]
}
}
]
the update video js code:
var requestOptions = {
part:'snippet',
id: String(id),
snippet:{ title: "ok update"}
};
var request = gapi.client.youtube.videos.update(requestOptions);
request.execute(nothing());
the request json:
[{"jsonrpc":"2.0",
"id":"gapiRpc",
"method":"youtube.videos.update",
"params": {
"part":"snippet",
"id":"nOoHrAR50f8",
"snippet":{"title":"ok update"}
},
"apiVersion":"v3"
}]
you can see here the id is the same as the list request json, but I still get the error respond:
[
{
"error": {
"code": 500,
"message": "Video not found",
"data": [
{
"message": "Video not found"
}
]
},
"id": "gapiRpc"
}
]
I also test on Link2, but also get 500 error.
You need wrap your updates in a 'resource' attribute:
gapi.client.youtube.videos.update({
fields: "snippet",
part: "snippet",
resource: {
id: "vid_id",
snippet: {
description: "updating vid",
}
}
});
Remember to set other attributes in the snippet (like categoryId, tags, etc.); otherwise, you'll get another error or they'll be unset.
Probably the best way to do this is to first retrieve the video snippet using gapi.client.youtube.videos.list and alter the snippet, then call gapi.client.youtube.videos.update passing in the altered snippet in the resource attrbute.

Categories

Resources