I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
Related
I am trying to create a Request via Axios JS to the API Route and trying to send the data from the database over the controller back to the view of the page. When I am just put an string as return value it is working.
I am always getting following a 500 Error.
JS File
function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
axios({
method: 'get',
url: '/api/zimmer/' + e.value,
responseType: 'stream'
})
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.data);
})
.catch(function(error) {
console.log(error);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
API Route:
Route::controller(MieterController::class)->group(function () {
Route::get('/zimmer/{id}', 'relocate_update')->name('api.get.zimmer');
});
Controller:
public function relocate_update($id) {
$zimmer_zu_objekt = Zimmer::findOrFail()->where('objekt_id', $id);
return response()->json(['alle_zimmer' => $zimmer_zu_objekt], 200);
}
I got it.
I changed it to VanillaJS and the main problem was my Eloquent Query in the Controller. Corret is
return Zimmer::where('objekt_id','=', $id)->get();
and used the fetch-method is JS:
fetch('/api/zimmer/' + e.value)
.then(function(response) {
zimmer_select.disabled = false;
console.log(response.json());
})
.catch(function(error) {
console.log(error);
});
How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}
i have a strange problem:
we have to make a project in IT, therefore we use AngularJS.
The problem is, when I use F5 for refresh, the page loads, but it is not able to show the right content again. There's just background and my title, everything in my UI-VIEW isn't there.
We have Login-Page with redirecting:
app.run(function($rootScope, $location, sessionFactory) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
let loggedIn = sessionFactory.isAuthenticated();
if (toState.authenticate && !loggedIn) {
event.preventDefault();
$state.go('login');
}
});
});
without this redirecting block, F5 works.
Otherwise I have to go to Login-Page and login again to get it work again.
I'm sorry guys, I'm new at programming. So if there's any code you need, just let me know. Hope someone can help.
UPDATE: this is our authentification_service.js
a group member wrote it. Does it help?
var app = angular.module('TheApp');
/**
* This service manages sessions: Retrieving token from server and storing token data.
*/
app.factory('sessionFactory', ['$http', 'jwtDecoder', function($http, jwtDecoder) {
var sessionFactory = {
sessionData: null
};
sessionFactory.login = function(username, password) {
//todo: encrypt password....
var user = { username : username, password : password};
// returns a POST request, success or error of that request
// must be handled by the caller of the login function
return $http({
method: 'POST',
url: 'rest/auth/login',
data: user
});
};
sessionFactory.logout = function() {
return $http({
method: 'POST',
url: 'rest/auth/logout',
data: this.sessionData
});
}
sessionFactory.deleteSessionData = function() {
this.sessionData = null;
}
sessionFactory.setSessionData = function(sessionData) {
this.sessionData = {
token: sessionData.token,
userData: jwtDecoder.getUserData(sessionData.token) // holds user id, todo: permissions
};
console.log(this.sessionData.userData);
};
sessionFactory.getToken = function() {
return this.sessionData.token;
};
sessionFactory.getUserId = function() {
return this.sessionData.userData.userId;
}
sessionFactory.isAuthenticated = function() {
return this.sessionData != null;
};
return sessionFactory;
}]);
/**
* This service injects authentification token in HTTP requests.
*/
app.factory('tokenInjector', ['$injector', function($injector) {
var tokenInjector = {
request: function(config) {
// cannot use sessionFactory directly, because else Angular will spot a circular dependency -> error
var sessionFactory = $injector.get('sessionFactory');
// if the user is logged in, add an Authorization header (with token) to each http request
if(sessionFactory.isAuthenticated()) {
config.headers.Authorization = 'Bearer ' + sessionFactory.getToken();
//config.url = config.url + "?token=" + sessionFactory.getToken(); // add token to request url
}
return config;
}
};
return tokenInjector;
}]);
/**
* Decodes JWTs received from the server with a JWT deconding lib
* and returns a useable result.
*/
app.factory('jwtDecoder', function() {
var jwtDecoder = {};
// extracts all needed frontend user data from token
jwtDecoder.getUserData = function(token) {
var payload = jwt_decode(token);
var userData = {
userId: payload.userId //,
//groupId: ?,
//permissions: payload.permissions, // is array of perm
};
return userData;
}
return jwtDecoder;
})
I am using Ionic Framework and WP-API to develop a mobile app for my Woocommerce based website.I am using the following URL to retriece JSON data about my products from the website -
http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK
When I try this URL from my browser, I get a perfect JSON response, with all the required details about my products. However, when i try calling the same URL through Ionic, the framework throughs an error.
UPDATE
$http.jsonp( postsApi ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
Please provide a working link to try it again.
Try using service:
app = angular.module('appName', ['ionic']);
app.factory('postService', function($http){
return {
all: function all() {
var url = 'http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK';
return $http.jsonp(url, {cache: true})
.success(function(data){
return data;
}).error(function() {
alert("Error");
});
}
}
});
app.controller("ItemController", function($scope,postService){
$scope.item = [];
postService.all().then(function(data){
data = data.data;
if(data.length == 0){
console.log('empty return');
}else{
$scope.item = data;
}
});
});
want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result