Modify Returned Response - arrays

I am trying to get a Session Key response to use in my future request inside a Zapier Session Authentication, however the response back from a successful authentication is "OK: hbsdakjdkaskjdfvbasdkjh". I need the hbsdakjdkaskjdfvbasdkjh extracted and then saved as the session key variable in the below zapier cli code
I am a little new to parsing JSON, but I think the response is actually raw... I tried a Regex but couldn't figure out the right statement and wondered if someone could help point me in the right direction.
The session URL params etc are working, and the Session Key responding after the OK: is actually correct and one I can use for the remainder of the session manually....
const options = {
url: 'https://theconsole.domain.com.au/api/auth.pl',
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'accept': 'application/json'
},
params: {
'AccountNo': bundle.authData.AccountNo,
'UserId': bundle.authData.UserId,
'Password': bundle.authData.Password
},
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return {
'sessionKey': results.sessionKey
};
});

Cool, so if your response is not json, you'll want to remove the z.JSON.parse line, since that'll throw an error.
As for pulling the key out of the response, success will depend on knowing that the response will always have a certain format. In this case, it sounds like it's OK: somekey.
If we can safely assume that there'll only ever be one space () and it's directly before the key, you can try something like:
// the rest of the code
respone.throwForStatus(); // important, assuming the server gives a non-2xx code for a bad auth
const sessionKey = response.content.split(' ')[1];
return {sessionKey}; // shorthand for {sessionKey: sessionKey}
Assuming those assumptions hold true, that should work!

Related

Django views not returning a value from a multiple parameter request?

I've been using vanilla Django as a backend to my React frontend. I'm trying to make a POST request using axios that passes a dictionary of 2 values to my django view, and so far on my front end the values are valid, the connection to the django url is made, but the only issue is the actual data being processed in the view. If I try to print the value, it returns as None. Heres what I have so far:
Relevant Code
views.py
def render_data(request):
reddit_url = request.POST.get('reddit_url')
sort = request.POST.get('sort')
print(reddit_url, sort)
users_data, count = run_data(reddit_url, sort)
data = {
'users_data': users_data,
'count': count,
}
return JsonResponse(data)
component.jsx
const APIcall = () => {
axios
.post(
`http://127.0.0.1:8000/reddit_data/`,
{
reddit_url: location.state.link,
sort: location.state.sort,
},
{
headers: {
"Content-Type": "application/json",
"X-CSRFToken": location.state.token,
},
withCredentials: true, //cors requests
}
)
.then((res) => {
console.log("YESSIR");
setLoading(false);
});
};
Expected/actual output
Ideally, the output would print the values from the request, but the actual result is just None, None.
What I tried
I tried using request.POST['reddit_url'] with no different results
Double checking the frontend values to make sure the POST call is going through with the correct values
I'll be honest I havent tried much I really cant understand this one
Turns out, my QueryDict was returning empty in my Django console while trying to print it, and I simply solved it by using var formData = new FormData(); appending my values, then using it as a parameter in my axios post to make a POST request.

Reactjs Api Call Not working in Yii2

I'm new to React js And I using Yii2 as my backend..! When I Send a API request to yii2 ,It Returns me the 500 Error.I don't know,Where I made a mistake.
Here is my React Js Code for API call,
fetch('localhost/learning-react/api/admin/signup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
fname:fname,
lname:lname,
email:email,
uname:uname,
passwd:passwd
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson['status']==='1')
{
alert(responseJson['msg']);
}
}
And This is My Yii2 Backend code,
public function actionSignup()
{
//$model = new TblUsers();
return "success";
}
Sorry For my Inability to finding mistakes in my code..!
First of all, 500 means generic server error. So you will need to post your error log as per my comment to help on that. However, I have found your code on the backend is wrong. You do not user restful controller in your code and as such it is not a REST API at all. So I advice you to read through Restful APIs in the Guide. That being said, you basically need to:
Create Restful controller by inheriting from yii\rest\Controller.
Return either Array, DataProvider or instance of yii\base\Model to have guarantee of automated serialization to JSON
so I will show you a simple example to give you an idea. Please read the guide to get in-depth insights on REST API with Yii2.
<?php
namespace app\modules\v1\controllers;
use yii\rest\Controller;
class LoginController extends Controller
{
public function actionSignup()
{
$model = new TblUsers();
//register a user
//return registred user
return [
'success' => true,
'member' => $model;
];
}
}
Let try the following, it may help.
You are making a rest post request, this means two things, first info will travel by POST request, and second dont forget its rest.
try opening the url in the browser, unless you define a rule it should open.
So go ahead open: http://localhost/learning-react/api/admin/signup you should see a "success" on the screen, or you will se the full 500 error printed.
If you were able to open the url on the browser, try the call again, and check your chrome debugger on the network tab. Look for the 500 error open it and read the error, it should be fully printed there on the response tab i.e.
when this is solved, don't forget to enable rules to allow only POST as request, and add the appropriate format for the response so you can consume it as json.
Yii::$app->response->format = Response::FORMAT_JSON;
Hope it helps debuggin.

Spotify API Post Request Add Tracks To Playlist - ERROR 400 BAD REQUEST

Im having what seems to be a very common error when working on the Spotify API adding tracks to a users playlist. In a previous fetch method I have obtained the users playlistId and am now trying to post tracks onto that playlist with that playlistId. I have followed the documentation but am obviously missing something, here is code:
` //userUd, playlistId, currentUserAccessToken, trackURIs are all defined
fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: {
'Authorization': 'Bearer ' + currentUserAccessToken
},
contentType: 'application/json',
method: 'POST',
body: JSON.stringify({
"uris": `[${trackURIs}]`
})
}).then(success => {
return success;
}).catch(err => {
console.log('here is your error', err);
})`
I did the GET request to authorize user - included scope for creating public playlist, in different code block which is working, here's that:
`let scopes = 'playlist-modify-public';
window.location.replace(https://accounts.spotify.com/authorize?client_id=${clientID}&scope=${scopes}&redirect_uri=${redirectURI}&response_type=token);`
Thanks a ton!
The JSON array needs quotes around each element in it. So each track should be quoted, like so:
{"uris": ["spotify:track:4iV5W9uYEdYUVa79Axb7Rh", "spotify:track:1301WleyT98MSxVHPZCA6M"]}
I think you're supplying an object names uris with an invalid array.
And, note you can pass the playlist items as query params too (instead of in the body), without using json. https://developer.spotify.com/web-api/add-tracks-to-playlist/

How To Setup Minimalist Authentication In Rails with React?

I am trying to set up a minimal layer of authentication between my Rails backend and my React front end, but I am running into some problems.
I cannot seem to find the cookie key value that the server passes down to my client. In the network tab, I see it in the response: Set-Cookie:_skillcoop_session=...., but when I use js-cookie to look for the above cookie, _skillcoop_session, I only see one called identity-token=... and its value is different from _skillcoop_session. How do I access _skillcoop_session in the browser?
What header key do I pass up to the server to signal to my backend to use 'this' header key to match up with the session it has stored off? In this post, Justin Weiss seems to suggest that I make the request to the server with a header like: Cookie: _skillcoop_session=....
Am I doing this all wrong? Would I be better off using a gem like devise?
Also in order to load the session in my other controllers, I have had to do something like session['init'] = true, and I learned to do this from this SO post. This seems hacky. Why do I have to manually reload the session in separate controller actions after I've set it previously in a different controller action in a different request?
I'm currently just stubbing out the user and the authentication -- all I want to do to get the plumping in place is set a session[:user_id] and be able to read that session data in other controller actions. For this I have two main files for consideration: UsersController and Transport.js. In UsersController I am just stubbing the session[:user_id] with the number 1 and in Transport.js I'd like to pass the cookie received from the server so that the backend can maintain a session between requests with a client.
Here is my controller:
class UsersController < ApplicationController
def create
session[:user_id] = 1
render json: user_stub, status: :ok
end
def show
puts "user id: #{session[:user_id]}"
# should return, 1, but is returning, nil...why?
render json: user_stub, status: :ok
end
private
def user_stub
{
id: 1,
email: params['email'] || 'fakeemail#gmail.com',
password: params['password'] || 'fake password'
}
end
end
Here is the main location of my app where I make my request to the server - it's in an abstraction I call Transport.js:
require('es6-promise').polyfill();
require('isomorphic-fetch');
var cookie = require('js-cookie');
const GET = 'GET';
const POST = 'POST';
function Transport() {
}
Transport.prototype.get = function(url, options = {}) {
return this.query(GET, url, null, options);
};
Transport.prototype.post = function(url, dataString, options = {}) {
return this.query(POST, url, dataString, options);
};
Transport.prototype.query = function(method, url, dataString, options = {}) {
var data;
if (dataString) {
data = JSON.parse(dataString);
}
switch(method) {
case GET:
return fetch(url, Object.assign({headers: {'Cookie': cookie.get('_skillcoop_session')}}, options, {
method: method
}));
case POST:
return fetch(url, Object.assign({
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}, options, {
method: method
}));
default:
throw new Error("This HTTP Method is not supported.");
}
};
module.exports = Transport;
According to this SO post, one cannot access the Set-Cookie header in JS. Thus, I suppose my attempts to handle Set-Cookie in the response headers was a fools effort.
According to the NPM package that I'm using to make HTTP requests, I need to pass {credentials: 'same-origin'} key value pair in the second argument to fetch, which will 'automatically send cookies for the current domain'. That did the trick -- the session object is available and contains the user_id that was set in the session in the previous request in a different action.
Yes. I changed up how I approached this problem. I leaned very heavily on this Reddit post. In short, I use ruby-jwt on the backend and store the token in localStorage on the front end. Each request out to the server will include the token in a header AUTHORIZATION.
In following steps 1 and 2, it looks like I no longer have to 'reload the session'.

what is Difference between $httpParamSerializerJQLike and json.stringify

Here i wrote simple code for saving data into api when i user data: $httpParamSerializerJQLike(savingdata) is Binding data into server side but when i use data: JSON.stringify(savingdata) its not Binding at server side what is the reason
this.saveEmp = function (savingdata) {
var sersave = $http({
url: Privateurl2 + 'SaveEmpData',
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded ;charset=utf-8'
},
// data: $httpParamSerializerJQLike(savingdata),
data: JSON.stringify(savingdata),
})
return sersave;
}
You ask
what is Difference between $httpParamSerializerJQLike and json.stringify
The answer is simple. The former produces a string in form-url-encoded format, the latter JSON. To illustrate...
const savingdata = {
foo: 'abc',
bar: 123,
baz: ['A', 'B']
}
$httpParamSerializerJQLike(savingdata)
// <- foo=abc&bar=123&baz%5B%5D=A&baz%5B%5D=B
JSON.stringify(savingdata)
// <- {"foo":"abc","bar":123,"baz":["A","B"]}
As for why one works with your server and the other does not; you are setting the request Content-type to application/x-www-form-urlencoded. If you attempt to send a JSON formatted request body, your server will fail to decode it because it does not match the format you specified.
Your server may be able to handle a JSON request payload (if it has been coded / configured to do so) in which case you can simply use the AngularJS defaults and use
return $http.post(Privateurl2 + 'SaveEmpData', savingdata)
This will set the Content-type to application/json and will use JSON.stringify to serialize the request payload.
If your server is not set up to handle requests in this format, the operation will obviously fail.

Resources