I want to receive a JSON object using Ruby. I've written this:
require 'sinatra'
require 'json'
post '/' do
push = JSON.parse(params[:payload])
"I got some JSON: #{push.inspect}"
end
And I'm sending:
var options = {
host: 'localhost',
port: 4567,
path: '/',
method: 'POST'
};
var myFirstJSON = { "payload" : { "headers" :
[{ "from" : from,
"to" : to,
"subject" : subject }],
"body" :
[{ "primeira_parte" : primeira_parte,
"segunda_parte" : segunda_parte,
"terceira_parte": terceira_parte }]
}};
req.write(JSON.stringify(myFirstJSON));
However, I'm getting this error:
TypeError - can't convert nil into String:
{"{\"payload\":{\"headers\":"=>{"{\"from\":\"test#test.com\",\"to\":\"test#test.com\",\"subject\":\"Testing\"}"=>{",\"body\":"=>{"{\"primeira_parte\":\"The following message to <test#test.com> was undeliverable.\\r\\nThe reason for the problem:\\r\\n5.1.0 - Unknown address error 553-'sorry, this recipient is not in my valid"=>"\\r\\nrcptto list (#5.7.1)'\",\"segunda_parte\":\"Final-Recipient: rfc822"}}}, "test#test.com\\r\\nAction: failed\\r\\nStatus: 5.0.0 (permanent failure)\\r\\nRemote-MTA: dns"=>nil, "216.75.35.163"=>{"\\r\\nDiagnostic-Code: smtp"=>nil}, "5.1.0 - Unknown address error 553-'sorry, this recipient is not in my validrcptto list (#5.7.1)' (delivery attempts: 0)\",\"terceira_parte\":\"Received: from unknown (HELO aws-bacon-delivery-svc-iad-1020.vdc.amazon.com) ("=>{"10.144.21.123"=>{")\\r\\n by na-mm-outgoing-6102-bacon.iad6.amazon.com with ESMTP"=>nil}}, "16 Apr 2011 14:11:15 0000\\r\\nReturn-Path: 0000012f5eb1cab3-09564031-57ef-4136-8cd7-9f368c5acd7d-000000#email-bounces.amazonses.com\\r\\nDate: Sat, 16 Apr 2011 14:23:20 0000\\r\\nFrom: tiago#tiagop.org\\r\\nTo: test#test.com\\r\\nMessage-ID: <0000012f5eb1cab3-09564031-57ef-4136-8cd7-9f368c5acd7d-000000#email.amazonses.com>\\r\\nSubject: Testing\\r\\nMime-Version: 1.0\\r\\nContent-Type: text/plain"=>nil, "\\r\\n charset"=>"UTF-8\\r\\nContent-Transfer-Encoding: 7bit\\r\\nX-AWS-Outgoing: 199.255.192.79\\r\\n\\r\\n<html><body><p> Helllooo </p></body></html>\\r\\n\\r\\n\"}]}}"}
What you want is a route like this:
post '/' do
push = JSON.parse(request.body.read)
"I got JSON: #{push.inspect}"
end
You're not form encoding the data, therefore it doesn't get set in params.
Related
TL;DR
I want Lucid ORM alternative to following PGSQL Query
INSERT INTO "api_logs" ("request_id", "request_url", "request_method", "request_data", "response_data", "remark", "created_at", "updated_at")
VALUES (uuid_generate_v4(), NULL, 'POST', '{
"test": "success"
}', '{
"test": "success"
}', 'test', now(), now());
I am using PostgresSQL with Adonis Node Framework, I have a table named api_logs with following schema:
id integer Auto Increment [nextval('api_request_logs_id_seq')]
request_id uuid
request_url character varying(255) NULL
request_method character varying(255) NULL [POST]
request_data json NULL
response_data json NULL
created_at timestamptz NULL
updated_at timestamptz NULL
I am trying to create a record using Adonis Lucid ORM, but it is returning exception.
Failed attempts:
await ApiRequestLog.create({
request_id : uuid.v4(),
request_url : request.url(),
request_method : request.method(),
request_data : request.all(),
response_data : response_data,
remark : 'Test Request with success response'
});
Error:
uuid is not defined
await ApiRequestLog.create({
request_url : request.url(),
request_method : request.method(),
request_data : request.all(),
response_data : response_data,
remark : 'Test Request with success response'
});
Error:
null value in column "request_id" violates not-null constraint
Thanks in advance!!!
Best.
After racking my brain, I could not find the solution with Adonis JS but I figured out the way by doing changes in PostgresQL.
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
Alter Table to add UUID while running
ALTER "request_id" TYPE uuid,
ALTER "request_id" SET DEFAULT uuid_generate_v4(),
ALTER "request_id" SET NOT NULL;
COMMENT ON COLUMN "api_logs"."request_id" IS '';
COMMENT ON TABLE "api_logs" IS '';
Worked for me, hope this will work for everyone.
I am running swagger with following code and getting error while performing POST operation..
swagger: "2.0"
info:
version: "0.0.1"
title: Hello World App
# during dev, should point to your local machine
host: localhost:10010
# basePath prefixes all resource paths
basePath: /
#
schemes:
# tip: remove http to make production-grade
- http
- https
# format of bodies a client can send (Content-Type)
consumes:
- application/json
# format of the responses to the client (Accepts)
produces:
- application/json
paths:
/hello:
# binds a127 app logic to a route
x-swagger-router-controller: hello_world
get:
description: Returns 'Hello' to the caller
# used as the method name of the controller
operationId: hello
parameters:
- name: name
in: query
description: The name of the person to whom to say hello
required: false
type: string
responses:
"200":
description: Success
schema:
# a pointer to a definition
$ref: "#/definitions/HelloWorldResponse"
# responses may fall through to errors
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
/postpath:
x-swagger-router-controller: hello_world
post:
description: add a new movie to the list
# movie info to be stored
operationId: postpath
parameters:
- name: title
description: Movie properties
in: body
required: true
schema:
$ref: "#/definitions/Movie"
responses:
"200":
description: Success
schema:
$ref: "#/definitions/GeneralResponse"
default:
description: Error
schema:
$ref: "#/definitions/ErrorResponse"
/swagger:
x-swagger-pipe: swagger_raw
# complex objects have schema definitions
definitions:
HelloWorldResponse:
required:
- message
properties:
message:
type: string
ErrorResponse:
required:
- message
properties:
message:
type: string
Movie:
type: object
properties:
title:
type: string
description: task object name
year:
type: number
description: task description
required:
- title
- year
GeneralResponse:
type: object
properties:
success:
type: number
description: returns 1 if successful
description:
type: string
description: a short comment
required:
- success
- description
Following is the hello_world.js behind that.
'use strict';
var util = require('util');
module.exports = {
hello: hello, postpath: postpath
};
function hello(req, res) {
// variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name}
var name = req.swagger.params.name.value || 'stranger';
var hello = util.format('Hello, %s!', name, 'how are you?');
// this sends back a JSON response which is a single string
res.json(hello);
}
function postpath(req, res) {
var isOpen = true; // Details omitted
var doorStatus = isOpen;
res.json('Test');
}
I am getting method not allowed exception..
Following is the stacktrace..
{ "message": "Route defined in Swagger specification (/hello) but
there is no defined post operation.", "allowedMethods": [
"GET" ] }
You have defined this:
paths:
/hello:
get:
but you want to also define POST:
paths:
/hello:
get:
- something
post:
- something else
When I try to create an envelope from a template I get a response of:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
Here's what I'm doing so far:
First I login, which returns
{ loginAccounts:
[ { name: '*****',
accountId: '*****',
baseUrl: 'https://demo.docusign.net/restapi/v2/accounts/******',
isDefault: 'true',
userName: '***** ********',
userId: '*******-*****-*****-*****-*********',
email: '********#*******.com',
siteDescription: '' } ] }
So then I take the baseUrl out of that response and I attempt to create the envelope. I'm using the hapi framework and async.waterfall of the async library, so for anyone unfamiliar with either of these my use of the async library uses the next callback to call the next function which in this case would be to get the url for the iframe, and with our usage of the hapi framework AppServer.Wreck is roughy equivalent to request:
function prepareEnvelope(baseUrl, next) {
var createEntitlementTemplateId = "99C44F50-2C97-4074-896B-2454969CAEF7";
var getEnvelopeUrl = baseUrl + "/envelopes";
var options = {
headers: {
"X-DocuSign-Authentication": JSON.stringify(authHeader),
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Disposition": "form-data"
},
body : JSON.stringify({
status: "sent",
emailSubject: "Test email subject",
emailBlurb: "My email blurb",
templateId: createEntitlementTemplateId,
templateRoles: [
{
email: "anemailaddress#gmail.com",
name: "Recipient Name",
roleName: "Signer1",
clientUserId: "1099", // TODO: replace with the user's id
tabs : {
textTabs : [
{
tabLabel : "acct_nmbr",
value : "123456"
},
{
tabLabel : "hm_phn_nmbr",
value : "8005882300"
},
{
tabLabel : "nm",
value : "Mr Foo Bar"
}
]
}
}
]
})
};
console.log("--------> options: ", options); // REMOVE THIS ====
AppServer.Wreck.post(getEnvelopeUrl, options, function(err, res, body) {
console.log("Request Envelope Result: \r\n", JSON.parse(body));
next(null, body, baseUrl);
});
}
And what I get back is:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
From a little googling it look like 'Non-static method requires a target.' is a C# error and doesn't really give me much indication of what part of my configuration object is wrong.
I've tried a simpler version of this call stripping out all of the tabs and clientUserId and I get the same response.
I created my template on the Docusign website and I haven't ruled out that something is set up incorrectly there. I created a template, confirmed that Docusign noticed the named form fields, and created a 'placeholder' templateRole.
Here's the templateRole placeholder:
Here's one of the named fields that I want to populate and corresponding data label:
As a side note, I was able to get the basic vanilla example working without named fields nor using a template using the docusign node package just fine but I didn't see any way to use tabs with named form fields with the library and decided that I'd rather have more fine-grained control over what I'm doing anyway and so I opted for just hitting the APIs.
Surprisingly when I search SO for the errorCode and message I'm getting I could only find one post without a resolution :/
Of course any help will be greatly appreciated. Please don't hesitate to let me know if you need any additional information.
Once I received feedback from Docusign that my api call had an empty body it didn't take but a couple minutes for me to realize that the issue was my options object containing a body property rather than a payload property, as is done in the hapi framework.
I'm trying to send a JSON file to my Node.js app via Protocol.HTTP. The file is correctly sent, but I can't access to an array. Here is the relevant code :
Client side
(...)
var vectorProtocol = new OpenLayers.Protocol.HTTP({
url: '/getcoords',
format: vectorFormat,
readWithPOST: true,
params: {
"code_company": "8501",
"data_company": [
{
"origin": "2013P00109",
"type": "LJ",
"naf": "5610A",
},
{
"origin": "2013P00110",
"type": "FJ",
"naf": "5481"
}
]
}
});
(...)
Server side, I try to build an array with only the "origin" field of my array "data_company":
function getCoords(params, callback) {
var arrOrigin = params.data_company.map(function(d) {
return d.origin;
});
(...)
}
And I get this error :
TypeError: Object [object Object] has no method "map"
It seems that my "data_company" is not recognized as an array but as an object. I tried to JSON.parse(params) before but I get another error :
SyntaxError: Unexpected token o
Anyway, I'm stuck. Do you have any clue to help me to solve this ?
Thanks
I am sending a JSON (from Client-Side) to a NodeJS Server like this:
$.ajax({
type: "POST",
dataType: "jsonp",
url: "www.xyz.com/save",
data: {
designation: "Software Developer",
skills: [
"",
"ASP.NET",
"PHP",
"",
"",
"",
"NodeJS",
"",
""
]
}
});
On the receiving end (i.e. the NodeJS Server), I print the JSON (with console.log) as follows:
save = module.exports = {};
save.setup = function( app ) {
app.get( '/save', function(req, res) {
console.log(req.query);
});
}
The problem is that it prints the following:
{
designation: "Software Developer",
skills: [
"ASP.NET",
"PHP",
"NodeJS",
]
}
i.e It is missing the empty-string values in the skills array (as I get it from req.query).
I have also checked the Network Panel (inside Developer Tools). It also shows the correct JSON.
Do anyone has any idea what may be going wrong ?
Connect (on which Express is built) uses the third-party qs module rather than the built-in querystring module to parse URL query strings.
Your data gets serialized by jQuery into the following query string:
designation=Software+Developer&skills%5B%5D=&skills%5B%5D=ASP.NET&skills%5B%5D=PHP&skills%5B%5D=&skills%5B%5D=&skills%5B%5D=&skills%5B%5D=NodeJS&skills%5B%5D=&skills%5B%5D=
(That's multiple parameters named skills[] which include the blanks.)
If I give that string to querystring.parse()—the built-in parser—I get the result you're expecting:
{ designation: 'Software Developer',
'skills[]':
[ '',
'ASP.NET',
'PHP',
'',
'',
'',
'NodeJS',
'',
'' ] }
If I give the string to qs.parse, I get the same result you're seeing in your app.
This behavior is an open qs issue, but it has been unresolved for over a year and a half. You could bug TJ about it or try to fix the issue yourself.
In the meantime, you can work around the bug by using querystring rather than qs. I'd just use url.parse to re-parse the original URL.
var url = require('url');
app.get('/', function(req, res) {
console.log(url.parse(req.originalUrl, true).query);
});