Why my request works with postman but not with vue.js axios? - vue.js

I've made a back using Flask, and a front using vue.js,
Why I make the request with postman it returns what I want but not with axios ...
for exemple :
this.$axios
.post('http://127.0.0.1:5000/getUserDataByMail', { mail: 'test#test.com' })
.then(response => {
console.log('this.userData')
console.log(response.data)
this.userData = response
}
)
Is treated by :
#app.route('/getUserDataByMail', methods = ['GET', 'POST'])
def getUserDataByMail():
args = request.args
mail = args['mail']
return jsonify(mail)
cur = mysql.connection.cursor()
dataCur = cur.execute('select * from userdata where email like "' + mail + '"')
if dataCur > 0:
data = cur.fetchall()
cur.close()
return jsonify(data)
cur.close()
But this result in an error 400 ...
POSThttp://127.0.0.1:5000/getUserDataByMail [HTTP/1.0 400 BAD REQUEST 4ms]
Uncaught (in promise) Error: Request failed with status code 400
Help me I'm losing my mind ! (:

Axios by default posts an application/json request body.
To read JSON payloads in Flask, you use request.json
content = request.json
mail = content["mail"]
I can only assume Postman works because you were posting an application/x-www-form-urlencoded request body or using URL query parameters.
To match what you're doing in Axios, make sure you post JSON

Related

Express res.send or res.json doesn't contain a body

I'm calling an API to fetch orders for a given user based on ID which are fetched from a third-party site. These are fetched correctly as a console.log them in the node server. But when I try to send the results back to the client neither res.send nor res.json results sending the data back to the client. Here is an example of an order from console.log:
{"customer":{"orders":{"edges":[{"node":{"id":"gid://shopify/Order/1234564564","lineItems":{"edges":[{"node":{"title":"Some title here"}}]}}}]}}}
Then on the client in the devtools when I console.log the response I get:
body:ReadableStream
locked:false
[[Prototype]]:ReadableStream
bodyUsed:false
headers:
Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"http://localhost:9000/api/getOrders?cid=gid://shopify/Customer/1234564564"
[[Prototype]]:Response
Any help is appreciated.
=== UPDATE ===
I've now even tried the most basic of examples and am getting the same response on the client:
app.get('/testExpress', (req, res) => {
res.send("Hello")
});
Thanks to #laurent here is how I was able to receive that response on the client:
fetch('/testExpress')
.then(async (r) => {
const resp = await r.text();
console.log(resp);
})
You should try to get the json out of the response by const json = await response.json().
These are the available methods to parse the response body depending on what you want:
Response.arrayBuffer()
Returns a promise that resolves with an ArrayBuffer representation of the response body.
Response.blob()
Returns a promise that resolves with a Blob representation of the response body.
Response.clone()
Creates a clone of a Response object.
Response.formData()
Returns a promise that resolves with a FormData representation of the response body.
Response.json()
Returns a promise that resolves with the result of parsing the response body text as JSON.
Response.text()
Returns a promise that resolves with a text representation of the response body.
https://developer.mozilla.org/en-US/docs/Web/API/Response
The Response object is a representation of the http response. You should try to receive the body of the response by using one of these methods or parsing the body from the readable stream response.body.

How to get authorization key in flask, sending headers from vue & axios?

I am facing a problem with the authorization of the headers. I am sending the authorization key, "Authorization" from my frontend
This code to get the token from the front and send it in each request
import axios from 'axios'
let axiosInstance = null
if(localStorage.getItem('auth') != null){
axiosInstance = axios.create({
withCredentials: true,
baseURL: 'http://127.0.0.1:5000/api/v1',
timeout: 50000,
headers: {'Authorization':'JWT ' + JSON.parse(localStorage.getItem('auth')).token}
})
}else{
axiosInstance = axios.create({
withCredentials: true,
baseURL: 'http://127.0.0.1:5000/api/v1',
timeout: 50000,
headers: {'Authorization': 'JWT ' + JSON.parse(localStorage.getItem('auth'))}
})
}
So, doing tests with a rest com ACR client everything works fine, the code shown below, simply gets the token and using the split() function to separate by spaces
this code
from flask import Blueprint, request, jsonify, make_response
from traits.validations import validationsToken
dirs = Blueprint("dirs", __name__)
#dirs.before_request
def verifyTokenMiddleware():
import json
res = validationsToken()
token_authorization = request.headers.get('Authorization')
token_headers = token_authorization.split(" ")
print(token_headers)
from ARC client the print is
but if it is sent from the front client of my view in the browser the response is
I know that the error says that objects of type null do not have the split() attribute, but when I print the token I am actually getting the token string.
Now one of the solutions that I have found is to send the token in the body, I don't know if it is the best practice, but I would like to send them through the header.
Why did it work from ARC, but not from my frontend?

Odoo controllers avoid json-rpc when type="json"

I've the following route:
#http.route([
'/whatever/create'
], auth="none", type='json', methods=['POST'], csrf=False)
which I'm using to send a post request with json data on its body.
Is there any way to avoid using json-rpc responses on routes of type="json"? I would like to just answer plain json.
If it is not possible, is there any way to get the json data placed on the body request by using `type="http"?
#http.route('/whatever/create', auth='public', methods=['POST'], type='http')
def index(self, **kw):
data = request.httprequest.data
return 'success'
Above code defined in Odoo
url = "http://localhost:8069/whatever/create"
param = {
"type_operation": "PTI",
"label": "",
}
headers = {'Content-type': 'text/plain'}
r = requests.post(url, data=json.dumps(param), headers=headers)
Above code i have requested from a py file
While sending request you should change Content-type
'Content-type': 'application/json' --- > 'Content-type': 'text/plain'
Also while returning it only accept String
return {'status': 'success'} ---> return 'success'

ADF Create Pipeline Run - Parameters

I need to trigger a ADF Pipeline via REST API and pass a parameter in order to execute the pipeline for the given ID (parameter).
With sparse documentation around this, I am unable to figure out how to pass parameters to the URL
Sample:
https://management.azure.com/subscriptions/asdc57878-77fg-fb1e8-7b06-7b0698bfb1e8/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/df-datafactory-dev/pipelines/pl_StartProcessing/createRun?api-version=2018-06-01
I tried to send parmaters in the request body but I get the following message depending on how params are sent
{
"message": "The request entity's media type 'text/plain' is not supported for this resource."
}
I tried using python requests :
import requests
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01"
payload = " \"parameters\": {\r\n “stateID”: “78787878”\r\n}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer adsasdasdsad'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
I tried to put the parameter in the payload (body)
Paramters can be passed within body
python sample:
import requests
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01"
payload = "{\"stateID\":1200}"
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer adsasdasdsad'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
You have to use a parameter name as post
url = "https://management.azure.com/subscriptions/adsad-asdasd-adasd-adasda-adada/resourceGroups/dev-rg/providers/Microsoft.DataFactory/factories/datafactory-dev/pipelines/pl_Processing/createRun?api-version=2018-06-01 -d '{"stateID"="78787878"}'
microsoft docs for your reference :
https://learn.microsoft.com/en-us/rest/api/datafactory/pipelines/create-run
You have to pass them as the POST body.
To pass more than one parameter the body this looks like:
{
"param1": "param1value"
,"param2":"param2value"
}

Google app api with freshdesk api error

On using the freshdesk api from google app script getting an error
"{"code":"invalid_content_type","message":"Content-Type header is set to . It should be set to application/json"}"
The code used for this
function hd_getTickets(){//using v2
var API_KEY = 'xxxxxxxxxxxxxx';
var headers = {'Content-type': 'application/json','Authorization': 'Basic ' + Utilities.base64Encode(API_KEY + ':X') };
var data = { "query":"\"priority:3\"" };
var ENDPOINT = 'https://xxxxxxx.freshdesk.com/api/v2';
var url = ENDPOINT + '/search/tickets';
var options = { 'method': 'get', muteHttpExceptions: true,'headers': headers,'payload' : JSON.stringify(data)};
var response = UrlFetchApp.fetch(url, options);
}
Changing the endpoint and removing the payload from options work so assuming authorization and header is fine
var url = ENDPOINT + '/tickets';
var options = {'method':'get','headers':headers, muteHttpExceptions: true};
Using postman this works
https://xxxxxxx.freshdesk.com/api/v2/search/tickets?query="priority:3"
with header set as
Content-Type:application/json
Authorization:Basic xxxxxxxxxxxxxxxx
You are sending a GET request to the API with the Payload variable in the options.
In my opinion payloads are used for POST requests.
Construct the URL with the query parameters and send it without the Payload.
Example: 'https://domain.freshdesk.com/api/v2/search/tickets?query="priority:3"'
See details here: HTTP GET with request body
Freshdesk API Doc: https://developers.freshdesk.com/api/#filter_tickets
Two issues found
1) web site does not support payload based get.
2) google apps doesn't support special characters in url.
Adding parameters to the original url and encoding the double quotes works.
var ENDPOINT = 'https://xxxxxx.freshdesk.com/api/v2';
var query ='query='+encodeURIComponent("\"priority")+":1"+encodeURIComponent("\"");
var url = ENDPOINT + '/search/tickets?'+query;
var options = {'method': 'get', muteHttpExceptions: true,'headers': headers};
var response = UrlFetchApp.fetch(url, options);