Meteor JS, pass json data as params to HTTP.call - ajax

I need to pass a json as params to HTTP.call.
My code is:
HTTP.call("POST", "URL_TO_MY_WS", {
params: {
"IdLavanderia": "304BEACD-9B9C-42B7-B90B-83D563A9C8FE",
"DettaglioListino": [{
"IdListino": "",
"NomeProdotto": "Gonna",
"DescrizioneBreveProdotto": "Gonna in pelle",
"DescrizioneLungaProdotto": "Gonna in pelle",
"CodiceProdottoListino": "GON002",
"PrezzoLisitno": "1",
"PercentualeSconto": "0",
"Prezzo": "1",
"AttivoAl": "",
"AttivoDal": "",
"DettaglioListino": [{
"Quantita": 1,
"IdProdotto": "fd97afce-6968-48de-9f86-21e1ada350dc"
}]
}]
},
headers: {
'Authorization': "MY_ACCESS_TOKEN",
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
}
}, function(error, result) {
if (!error) {
console.log(result)
}
});
But using command "meteor debug" i see that params are passed as query string array.
Network tab show this:
IdLavanderia=304BEACD-9B9C-42B7-B90B-83D563A9C8FE&DettaglioListino[]%5BIdListino%5D=&DettaglioListino[]%5BNomeProdotto%5D=Gonna&DettaglioListino[]%5BDescrizioneBreveProdotto%5D=Gonna......
How can i force to pass in json format?

According to documentation, you just have to place your object in data field, rather than in params field.

Related

Need to return the response from .then() in cypress

I am trying to return the value of .then() and trying to use in another method but I am getting an error and couldn't do that. Please help me with this.
Is there any other way for returning this
test () {
var a = cy.request({
method: 'POST',
form: true,
url: 'https://......../token',
headers: { "Accept": "application/json, text/plain, /", "referer-domain": referer_domain, "Content-Type": "application/json;charset=UTF-8" },
body: {
"client_id": "..",
"client_secret": "....",
"username": username,
"password": password,
"grant_type": "password",
"scope": ""
}
})
.then(response => { return response })
return a;
}
If you want to return it as a chainable value of the function use cy.wrap()
cy.get('someElement')
.then(element => {
//some code
return cy.wrap('the value or action I need to retun)
}
.then(returnedValue => {
some code that can use it
}
If you want to access it as a variable in the code later you can use as()
cy.get('someElement')
.then(element => {
//some code
cy.wrap(result).as('resultAllias')
}
cy.get('#resultAllias')
.then(result => {
//some code to use the result
}
I know this question is old, but in case anyone comes across this question like I did, the issue is you're writing synchronous code against Cypress functions that are async.
The .then() callback attached to your cy.request() is going to be executed long after your function already returned, thus it will always result in var a being undefined.
The proper way to return the response it to simply return the cy.request() function and to use the .then() callback in the test to interact with the response.
test () {
// var a = cy.request({
return cy.request({
method: 'POST',
form: true,
url: 'https://......../token',
headers: { "Accept": "application/json, text/plain, /", "referer-domain": referer_domain, "Content-Type": "application/json;charset=UTF-8" },
body: {
"client_id": "..",
"client_secret": "....",
"username": username,
"password": password,
"grant_type": "password",
"scope": ""
}
})
// .then(response => { return response })
// return a;
}
// Test code
it('works', () => {
test().then(response => /* utilize the response here */);
});

How can i post json and image at the same time? Vuetify + axios

I got the data with json format but also got image in same form. How can I post the image and json data to laravel request at the same time?
Data Object:
{
"pwra_uuid": "",
"purchase_order_uuid": "26729191407884625",
"group_tasks_uuid": "26729191407884553",
"pwra_code": "HIS-CPPS-00281",
"pwra_dt": "2020-08-25",
"time": "05:25",
"task_name": "fdsafdsa",
"specific_location": "fdsafdsa",
"time_session": "AM",
"status": "",
"employees": [
"26535933801136175",
"26535933801136183",
"26535933801136169"
]
}
Vue js code:
export default {
data() {
return {
chosenFile: null,
pwra: [],
};
},
methods: {
create() {
let data = this.pwra;
formData.append("image", this.chosenFile);
formData.append("data", data);
console.log(data);
axios.post("/pwra", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
},
},
};
Laravel Code:
public function store(Request $request)
{
$requestData = $request->all();
}
Given your complex data object (complex meaning it's not just a flat key / value map), your best bet is to stringify it as JSON and have your server-side code parse it to an array.
For example
formData.append("data", JSON.stringify(data));
and on the server-side, something like this
$data = json_decode($request->input('data'));

Axios and fetch gives empty mapping in Golang even when url-encoded (header is added)

I'm using axios to send http requests ( i used fetch also but it gives the same result ).
axios.post("http://localhost:3000/login",
{
answer: 42
},
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
In my go file I'm logging the response
func post(req *http.Request, res http.ResponseWriter) {
req.ParseForm()
fmt.Println(req.Form)
}
The log is as follows :
map[{"answer":42}:[]]
However i want it to be as follows :
map["answer":[42]]
(I get such when i use postman)
What is the issue with this.
Outgoing data for reference
UPDATE
I used request ( built-in with nodejs) and also with jQuery ajax. Both of them work well.
Its just with axios and fetch which is not working
Here is the code :
request
The following code using nodejs request
var request = require("request");
var options = { method: 'POST',
url: 'http://localhost:3000/login',
headers:
{
'cache-control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' },
form: { answer: '42' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
jQuery ajax
The following is my jQuery code
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:3000/login",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
},
"data": {
"answer": "42"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
However, I am still unable to get axios and fetch to work. If someone finds it please update the answer
You need something like this:
var querystring = require('querystring');
axios.post('http://localhost:3000/login', querystring.stringify({'answer': 42},headers: {
'Content-Type': 'application/x-www-form-urlencoded'
});
You can set query string parameters using the params config option,
It will definitely works:
axios.post("http://localhost:3000/login", "", {
params: {answer: 42},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
To find out more please read this https://github.com/axios/axios/issues/350#issuecomment-227270046

JIRA Rest API error. Unrecognized token creating a issue

No luck in adding a issue via AJAX and the REST API. I can get it to work with Postmen, unfortunatly, can't get it with an Ajax request.
The JSON I create is fine, the post request also. The issuetype is something I created myself, using Bug gives the same problem. See the JSON object created, my error and my code:
JSON object (this is a snippet from console.log):
The Error
0: "Unrecognized token 'fils5poet5': was expecting 'null', 'true',
'false' or NaN↵ at [Source:
org.apache.catalina.connector.CoyoteInputStream#7b958ed2; line: 1,
column: 21]"
jira = {
fields : {
project : {
key : "CIC"
},
summary : "test",
description: "test",
issuetype : {
name : "Sandbox item"
}
}
};
console.log(jira); //Also see image at top of this post.
// Submit to Jira api
$.ajax({
type : "POST",
dataType : "JSON",
url : configuration.api_url,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic ItsAWrap!(itworks...)"),
xhr.setRequestHeader ("Content-Type", "application/json");
},
data : jira,
success : (function(response) {
//Do something
}})
You need to JSON.stringify your jira variable before you send it.
You could try something like this:
jira = {
"fields":
{
"project":
{
"key": "CIC"
},
"summary": data["story.name"],
"description": data["story.notes"],
"issuetype": { "name": "Sandbox item" }
}
};
//THIS BADASS FUNCTION!!!
jira = JSON.stringify(jira);
$.ajax({
type : "POST",
url : configuration.api_url,
dataType : "JSON",
async : false,
headers: {
"Authorization": "Basic YeahSomethingInAWrap",
"Content-Type": "application/json",
"Accept": "application/json",
"Cache-Control": "no-cache"
},
data : jira,
success : (function(response) {
// Hide loader
l.removeClass("show");
// Alert Success Message
alert("Melding succesvol ontvangen, bedankt!");
// Close dialog
$(".chrome-extension-dialog a.close").trigger("click");
})
});

JSON format being POSTed incorrectly to /create in rails

using rails 2.3.8.
I'm getting this:
[
[0] "0",
[1] {
"name" => "Section",
"contents" => {
"0" => {
"name" => "RENAMED!",
"id" => "1"
}
}
}
]
notice the [0] and the [1]
but in my post, I formatted the JSON like this:
[ {
"name":"Section",
"contents":[
{
"id":1,
"name":"RENAMED!"
}
]
}, .. more of this type of structure [
so, why is rails adding the additional array?
Here is how I'm posting the object:
$j.ajax({
type: "POST",
url: 'http://url/objects/create/',
dataType: 'text',
async: false,
data: data_obj,
success: function () {
alert("sent");
}
});
UPDATE
data_obj = {
"my_object":{
"name":"hello there, I am JSON!",
"template_id":1,
"variables":{
"hello":"there",
"me":"you"
},
"sections":[
{
"name":"Section",
"contents":[
{
"id":1,
"name":"RENAMED!"
}
]
},
{
"name":"section2",
"contents":[
{
"name":"something",
"body":"nothing"
},
{
"id":2,
"name":"I renamed you",
"variables":{
"hello":"i'm amazing"
}
}
]
}
],
"attachments":[
{
"media_id":1
}
]
}
}
Rails is not adding the extra element to the json array. That's happening on the browser.
Check your javascript carefully for an "edge case" of adding an empty element to the array. Eg how are you initializing the array.
If you're not convinced by the above on where the bug is, add a breakpoint before the ajax call and examine the data_obj array.
ps. it should be an array, but you've named it data_obj. Are you treating it as an object at some point? Are you setting the first element to be at index 1? (That would be a bug.) You should only push values onto the array.
ADDED I think the problem is that you're not sending the data as json.
The default for sending data to the server is key/value pairs.
Try
$j.ajax({
type: "POST",
url: 'http://url/objects/create/',
dataType: 'text', // what you are expecting to be returned from server
async: false,
data: {json: JSON.stringify(data_obj)},
success: function () {
alert("sent");
}
});
See post. You may also have to set the mime-type. The post shows how.
alt for the structure:
...
data: {my_object: JSON.stringify(data_obj.my_object)},
...

Resources