Wildcard in Angular http.get? - json

I have multiple JSON files in one directory, and I am going to build the view contents from those JSON files. The JSON files are identical in structure.
What is the correct syntax for loading multiple JSON files for use with ng-repeat? I tried with this, but it throws a permission denied error (the view is loaded via a route, if it matters. Still learning Angular...).
I use these:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
Snippet from the view:
<div ng-controller="releases">
<article ng-repeat="album in albums">
{{ album.artist }}
</article>
</div>
Controller:
myApp.controller('releases', function($scope, $http) {
$scope.albums = [];
$http.get('contents/releases/*.json')
.then(function(releases) {
$scope.albums = releases.data;
console.log($scope.albums);
});
});
The JSON files are like this:
{
"artist" : "Artist name",
"album" : "Album title",
"releaseDate" : "2015-09-16"
}
The error message is:
You don't have permission to access /mypage/angular/contents/releases/*.json on this server.
If I use an exact filename, for example $http.get('contents/releases/album.json'), I can access the data correctly. But naturally only for one JSON, instead of the 11 files I have.
In a previous site I have done with PHP, I used an identical method, and there I could access the same files with no problem. For both, I'm using WAMP server (Apache 2) as the platform.
Could it still have something to do with the Apache config? The reason I don't think it is that, is because it does work in PHP like this:
// Get release data
$releasesDataLocation = 'contents/releases/*.json';
$releasesDataFiles = glob($releasesDataLocation);
rsort($releasesDataFiles); // Rsort = newest release first, comment out to show oldest first
// Show the releases
foreach($releasesDataFiles as $releaseData) {
$release = new Release($releaseData);
$release->display();
}

Wildcard AFAIK in such URLs is not allowed. You should build a server side endpoint that should read all the files in your directory on server, concatenate and return the response to you.
For eX: you could expose a GET URL: /api/contents/releases
and server side handler of it can read the directory containing all release JSONs and return to you.

Related

How can I show image from express server on Vue app?

I'm currently having problem with displaying image from db. In my DB (Sequelize MySQL), my columns looks like this.
Database
You can see that there is path, which is showing path to file on server. (Express server using multer to upload photos).
How Am I able to show this on my frontend? I was trying everything, but I cannot figure solution.
When I open my server folder and copy path of file there, I get path like this:
Path
When I put it in chrome, I can see that image, but when I try to display it in frontend, I'm not that lucky.
Here is my function on backend to get image.
async getOneImage (req,res){
try{
const getOneImage = await CaseImage.findOne({ where: {CaseId: req.params.CaseId, id: req.params.id}});
if (getOneImage == null) {
res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.' });
}
res.send(getOneImage);
}
catch (err) {
console.log(err);
res.status(400).send({ message: 'Nepodarilo sa načítať fotografie, skúste to neskôr.'});
}
},
Maybe should I change that response to binary or? I don't understand this topic cleary as you can see.
Thank you all for help and sorry if question is not correctly formated or named.
Ok so I tried, now I have request to node server but I get response 404 cannot get... so I'm assuming that problem is somewhere in my express settings...
this.imageSrc = http://localhost:3000/${data.path}.png
this is full url.. but response is 404.
http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png
edit.
So, this is my front-end.. You can see that I'm sending response to correct path.
frontend request
Here you can see how my backend setting of express looks like.
Express
And here is response that I'm getting when I send request to backend.
Response
But I'm still not able to see image in vue. When I check I see only blank space and in console is this reply:
"GET http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png 404 (Not Found)"
And in network tab is this.
Network tab
If you have correct paths to the images in your database you simply render them with an tag. Make sure the path to the file is complete, or relative to your static assets folder.
In your case the path seems to be some mix of static/uploads/hash and the filename problem.png.
This means the full url to the file is most likely something like:
domain.com/static/uploads//.png. The domain.com part will most likely be localhost: if you are working locally. On a production server this will be your domain you are hosting your app on.
PS. your second image is a full file path on your system, this wont be visible on a server.
So you have this static folder.
If you are not already serving this static folder with express, see this explanation on how to serve a static folder.
Once you fetch your image in the frontend you will have an image object something like this:
{
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
}
Your img tag in your html file should look as follows.
<img src="http://localhost:{PORT_OF_EXPRESS_SERVER}/static/uploads/abcdefg.........png"/>
Because you're using vue.js here is an example with axios.
MyComponent.js
import axios from 'axios';
export default {
data: () => {
return {
imageUrl: ''
}
},
mounted(): async () => {
// this route here must match what you defined in your backend
const { data } = await axios.get('/image/2/5')
console.log(data);
/** {
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
} **/
// now we set the imageUrl, assuming your express port is 1337
this.imageUrl = `http://localhost:1337/${data.path}`;
}
}
MyComponent.html
<template>
<div id="my-component">
<img :src="imageUrl"/>
</div>
</template>
<script src="./MyComponent.js"></script>

Importing JSON file in Cucumber Protractor framework

I want to keep my test data in a JSON file that I need to import in cucumber-protractor custom framework. I read we can directly require a JSON file or even use protractor params. However that doesn't work. I don't see the JSON file listed when requiring from a particular folder.
testdata.json
{
"name":"testdata",
"version":"1.0.0",
"username":"1020201",
"password":"1020201"
}
Code in the Config.js
onPrepare: function() {
var data = require('./testdata.json');
},
I don't see the testdata.json file when giving path in require though its available at the location.
I wish to access JSON data using data.name, data.version etc.
Following is my folder structure:
You should make sure your json file is located in the current directory & and in the same folder where your config file resides as you are giving this path require('./testdata.json'); -
There are many ways of setting your data variables and accessing them globally in your test scripts -
1st method: Preferred method is to use node's global object -
onPrepare: function() {
global.data = require('./testdata.json');
},
Now you could access data anywhere in your scripts.
2nd Method Is to use protractor's param object -
exports.config = {
params: {
data: require('./testdata.json');
}
};
you can then access it in the specs/test scripts using browser.params.data

Angular resource 404 Not Found

I've read other posts that have similar 404 errors, my problem is that I can correctly query the JSON data, but can't save without getting this error.
I'm using Angular's $resource to interact with a JSON endpoint. I have the resource object returning from a factory as follows:
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' });
});
My JSON is valid and I can successfully use resource's query() method to return the objects inside of my directive, like this:
var item = Product.query().$promise.then(function(promise) {
console.log(promise) // successfully returns JSON objects
});
However, when I try to save an item that I've updated, using the save() method, I get a 404 Not Found error.
This is the error that I get:
http://localhost:3000/api/products.json/12-34 404 (Not Found)
I know that my file path is correct, because I can return the items to update the view. Why am I getting this error and how can I save an item?
Here is my data structure:
[
{
"id": "12-34",
"name": "Greece",
"path": "/images/athens.png",
"description": ""
},
...
]
By default the $save method use the POST verb, you will need to figure out which HTTP verbs are accepted by your server en order to make an update, most modern api servers accept PATCH or PUT requests for updating data rather than POST.
Then configure your $resource instance to use the proper verb like this :
app.factory('Product', function($resource) {
return $resource('api/products.json', { id: '#id' }, {'update': { method:'PUT' }});
});
check $resource docs for more info.
NOTE: $resource is meant to connect a frontend with a backend server supporting RESTful protocol, unless you are using one to receive data & save it into a file rather than a db.
Otherwise if you are only working with frontend solution where you need to implement $resource and have no server for the moment, then use a fake one, there is many great solutions out there like deployd.
You probably don't implement POST method for urls like /api/products.json/12-34. POST method is requested from angular for saving a new resource. So you need to update your server side application to support it and do the actual saving.
app.factory('Product', function($resource) {
return $resource('api/products.json/:id', { id: '#id' });
});
Try adding "/:id" at the end of the URL string.

Angular $http not working as expected

I am new to angular and trying to consume a basic back end service that I created using laravel. It is a basic Todo application and I am trying to fetch all the users resource for now.
If you go to the following URI, it will give back the all the users in the application:
Link to the URI
The code in my angular file looks like
var testing = angular.module('testing', []);
testing.controller('MainCtrl', function($scope, $http){
$scope.hello = "Hello World!";
$http.get('users.json').success(function(data){
$scope.users = data;
});
});
Now when I pass the URI in the parameter of $http.get method, I don't see any data. I have tried {{ users | json }} in my main index file to see the dump output. It simply doesn't work. But when I copy just the data array in the response and save it to a json file, it works perfectly.
Now the json that is returned from the web service has slightly more information like status and messages. How do I remove them when fetching them in Angular so that it works or is there a way I can have them returned and then extract them somehow from the whole data that has been returned?
If here http://todoapi.rohanchhabra.in/users is response from your server you should update your $http call to :
$http.get('users.json').success(function(response){
$scope.users = response.data;
});
if you requesting json file from your local iis make sure that it can serve .json files

DART lang reading JSON file saved in the client, i.e. without using a server

I'm trying to read data from JSON file, using the blow code:
void makeRequest(Event e){
var path='json/config.json';
var httpRequest= new HttpRequest();
httpRequest
..open('GET', path)
..onLoadEnd.listen((e)=>requestComplete(httpRequest))
..send('');
}
this worked very well when the app run as http:// .../ index.html, but gave the below error when trying to open it as file:///.../index.html
Exception: NetworkError: Failed to load 'file:///D:/DartApp/web/json/config.json'. main.dart:53makeRequest main.dart:53<anonymous closure>
Is there another way, other than httpRequest that can read JSON file from client side!
I understand I've 3 options, 2 of them only can use HttPRequest, which are:
saving the file of the server, and reading it from the server => can use HttpRequesit
saving the file on the server, and reading it from the client => can use HttpRequesit
saving the file on the client, and reading it from the client itself => CAN NOT use HTTPRequest
I'm searching for the way to do the 3rd option, which is like making off-line Android App using webview, or making off-line Chrome packaged app, i.e I do not want to use a server at all. thanks
thanks
If all you need is the data in the json file, you can just include that data in your .dart files (as a Map variable/constant, for example).
Map config = {
"displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
};
If you need the actual json, you can put in a String. Something like:
const configJson = '''
{ "displayName": "My Display Name",
"anotherProperty": 42,
"complexProperty": {
"value_1": "actual value",
"value_2": "another value"
}
}
''';
The json data can be in a separate .dart file, which can be included as part of the same library (through part of ...), or imported (import 'package:mypackage/json.dart';).
If you're looking for something that you can change and the changes are persisted, you're going to need to use some sort of offline storage, which can be web storage if you're running in a browser. You can use the approach above to define inital config data, store it in web storage, and from then on read and edit it from there.
[Previous answer below, before original question was edited.]
Sorry, read "client side", thought "server side". My mistake.
If by "client side" you mean "running in a browser", and you're trying to access a json file which is on the server, then no, there isn't any other way, other than an http request. In fact, that's the only way to read any file on the server, not just json ones. (Well, I guess you could open a WebSocket and stream the content, but that doesn't seem to be a solution you're looking for.)
[Old solution below, before my mistake (server vs client) was pointed out.]
Try:
// THIS DOESN'T WORK IN A BROWSER ENVIRONMENT (aka client side)
import 'dart:io';
import 'dart:convert';
// ...
new File('json/config.json')
.readAsString()
.then((fileContents) => json.decode(fileContents))
.then((jsonData) {
// do whatever you want with the data
});
This poor example works fine in the chrome dev editor dart web app example.
Using HttpRequest.getString works fine with filename and path.
Chris has a good write for json web service stuff at
https://www.dartlang.org/articles/json-web-service/
import 'dart:html';
import 'dart:convert';
void main() {
HttpRequest.getString('json/config.json').then((myjson) {
Map data = JSON.decode(myjson);
var version = data["version"];
var element = new DivElement();
element.text = "version = $version";
document.body.children.add(element);
});
}