Send multiple parameters when axios upload image - symfony

I'm uploading images with formdata and axios. I'm using symfony for my back end and I need to access my image file and other parameter both. This is my axios code.
axios.post(testUp, { data: formData, ad: 12 }, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
});
And here is my symfony code.
/**
* #Route("/test_up", name="test_up", methods={"GET","POST"})
*/
public function testUp(Request $request, CarRepository $carRepository) {
dd($request->files->all());
}
Unfortunately I'm getting null as output. I'm getting the formdata from image uploaded and it's a formdata object. It works if I do this but need both parameters.
axios.post(testUp, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
alert('*');
console.log(response);
});
but I need to send other parameter too.

You cant mix FormData with JSON. It is related question
Send FormData object AND an additional parameter via ajax
If you have only one parameter - ad = 12 I recommend to use code:
axios.post(testUp + "?" + (new URLSearchParams({ad: 12})).toString()
, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
alert('*');
console.log(response);
});

On Symfony side you should use a form so you can receive many type of data. See documentation here: https://symfony.com/doc/current/forms.html
On vuejs/axios side, you just cant send json content AND form data content at the same time (as it is 2 different type of data). But you can add some content to your form data (just like you can have a file with other fields in your Symfony form).

Related

Fetching resources from google analytics services using HTTPS by Wix fetch function

How should I fetch data using Wix-fetch function?
I followed this google analytics API tutorial, this tutorial using post function for getting JSON data, I used WIX fetch function to get JSON file, but the return object is undefined.
What did I miss?
fetch( "https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body' : JSON.stringify({
'grant_type': 'authorization_code',
'code': URLCode,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'redirect_uri': 'https://www.mydomain.or/ga/oauth2callback'
})
} )
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then( (json) => console.log(json.someKey) )
.catch(err => console.log(err));
UPDATE
STEP 1
I used this URL to generate the CODE
wixLocation.to("https://accounts.google.or/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/userinfo.email&redirect_uri=https://www.mydomain.or/ga/oauth2callback/&access_type=offline&response_type=code&client_id=XXXXXXXXXXXXXXXXXX")
I get the CODE from the callback URL
Step 2
I used this code for the HTTP postman request
The redirect URI in step 1 and 2 is the following (the second one):
Step 1:
There needs to be an exact match between the redirect URI configured in the client id in the google developers console and the URL to get the code authorization.
The URL should be built as shown in the tutorial you linked (if you need a refresh token, you can add the access_type=offline)
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics&redirect_uri=<redirect_uri>&response_type=code&client_id=<client_id>
After you enter the URL, you will be provided with an authorization window. Once you authorize, you will be redirected to the <redirect_uri> you provided earlier. You will find the code as the first parameter in the URL query. e.g. <redirect_uri>/?code=<auth_code> ...
Since the access token is for one-time use only, if you will need it again, you will have to get a new <auth_code>.
Step 2 (Postman query example):
If you got the access_token correctly and you want to check now with WIX. Get a new <auth_code> (as said, the access token is given once) and set the code as follows:
import { fetch} from 'wix-fetch';
$w.onReady(function () {
const data = `grant_type=authorization_code&code=<your_authorization_code>&client_id=<your_client_id>&client_secret=<your_client_secret>&redirect_uri=<your_redirect_uri>`;
fetch("https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body': data
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
})
.then((json) => console.log(json.access_token))
.catch(err => console.log(err));
});

Rails API not receiving fetch POST data from body

I have a route in Rails API '/api/pay'. My client side post request successfully hits the controller action, however nothing I send in the body: JSON.stringify('...') gets through to the back-end. Other post requests I have made work just fine with the same format.
export const payForItem = (payData) => {
return dispatch => {
dispatch(payForItemStart());
// ?userID=${data.userID}&adID=${data.adID}&price=${data.price}
const data = {userID: payData.userID, adID: payData.adID, price: payData.price}
fetch(`/api/pay`, {
method: 'POST',
header: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
Here is what payData looks like.
Rails Api back-end params
Probably you've got typo in headers section. Should be plural headerS with s:
headers: {
"Content-Type": "application/json"
}

Angular 2 POST don't send data to ASP.NET server

I would like to send data from client to ASP.NET MVC server using POST method. Web api action was called, but data haven't been sent to server. When I open Fiddler, i see data.
Here is my code:
Client
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/app/api/Users/', 'hello', { headers: headers, withCredentials: true })
.subscribe(user => {
console.log(user);
});
Server
[HttpPost]
public void Post([FromBody]string data)
{
//data is null
}
Where is the problem? Thanks for any advices.
The value is not form encoded but that is what you specify in your content-type header. Change the value to this:
'=hello'
Full call
this.http.post('http://localhost/app/api/Users/', '=hello', { headers: headers, withCredentials: true })
.subscribe(user => {
console.log(user);
});
When using application/x-www-form-urlencoded, you have to use formdata:
let data = new FormData();
data.append('data': 'hello');
ASP.NET won't deserialize the body if you don't specify the correct content-type and give clue about the match between the received body and the name of variables.
One possibility is to serialize the body to JSON, with matching variable names, like that :
let model = { data: "Hello" }
let req = new Headers();
req.headers.append('content-type', 'application/json');
let body = JSON.stringify(model);
this.http.post(url, body, req).subscribe(...)

$http.post not working with JSON data

I am building an application using AngularJS and I have a login form from which I want to send JSON data as request body.
In my controller;
$scope.credentials = {userid: $scope.userid, password: $scope.password};
$scope.login = function () {
$http({
method : 'POST',
url : 'http://localhost/login.json',
data : $scope.credentials,
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
// code
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status);
});
};
But when I am submitting the form POST request is not performing and I am getting a message in the console like;
0 function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
What am I doing wrong here?
If I changed the line
headers: {'Content-Type': 'application/json'}
to
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
the POST request is making. But I don't want to send it as form values instead I want to send the request as JSON.
You should encode javascript object to corresponding mime-type data in order to post data. If you are using jQuery, try to use $.param($scope.credentials) instead of just $scope.credentials.
I think the problem is that you're POSTing to http://localhost/login.json which is not any script that is able to receive POSTrequests with form data.

jquery-ajax post values to http-generic-handler don't return anything

I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.

Resources