vuejs: the correct path of local json file for axios get request - json

In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)

In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.

If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json

For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}

When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},

I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}

You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}

Related

Returning json from .csv asset in nuxt api

Using Nuxt 3, I am struggling to do something that appears simple: I would like to get a list of restaurants from an api served by nuxt/nitro in order to use it on the client side. My original file, is a .csv file stored under assets/: assets/list.csv.
Here is what I have in my component .vuefile:
//...
const { restaurants } = await useFetch('/api/restaurants')
//...
And the content of server/api/restaurants.js:
import csv from 'csvtojson'
export default defineEventHandler(async(event) => {
const data = await csv().fromFile('~/assets/list.csv')
return { data }
})
But I get an error "[500] File does not exist". I've tried many variants but always get an error here or there. Could you help me figure out the solution? Thanks.
Actually solved by realizing the following:
As the doc suggests, the assets/ directory is for assets that are processed by the bundler (Vite or Webpack). Nuxt won't serve files in the assets/ directory unless nuxt.config.ts is configured with the appropriate loader (e.g. a csv loader). Hence the 500 error.
Nuxt Content, on the other hand, is useful to automatically parse a .csv file located in the content/ directory:
In nuxt.config.ts:
modules: ["#nuxt/content"]
In the component .vue file, the following will expose the parsed csv in data.body:
const { data } = await useAsyncData("list", () => queryContent("/list").findOne())
The beauty of nuxt is that you don't need to import anything, it does it for you.

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

fs.readFileSync cannot find file when deploying with lambda

In my code I am calling a query from my lambda function
let featured_json_data = JSON.parse(fs.readFileSync('data/jsons/featured.json'))
This works locally because my featured.json is in the directory that I am reading from. However when I deploy with serverless, the zip it generates doesn't have those files, I get a
ENOENT: no such file directory, open...
I tried packaging by adding
package:
include:
- data/jsons/featured.json
but it just doesn't work. The only way I get this to work is manually adding the json file and then change my complied handler.js code to read from the json file in the root directory.
In this screenshot I have to add the jsons then manually upload it again and in the compiled handler.js code change the directory to exclude the data/jsons
I want to actually handle this in my servereless.yml
You can load JSON files using require().
const featured_json_data = require('./featured.json')
Or better yet, convert your JSON into JS!
For working with non-JSON files, I found that process.cwd() works for me in most cases. For example:
const fs = require('fs');
const path = require('path');
export default async (event, context, callback) => {
try {
console.log('cwd path', process.cwd());
const html = fs.readFileSync(
path.resolve(process.cwd(), './html/index.html'),
'utf-8'
);
const response = {
statusCode: 200,
headers: {
'Content-Type': 'text/html'
},
body: html
};
callback(null, response);
} catch (err) {
console.log(err);
}
};
I recommend looking at copy-webpack-plugin: https://github.com/webpack-contrib/copy-webpack-plugin
You can use it to package other files to include with your Lambda deployment.
In my project, I had a bunch of files in a /templates directory. In webpack.config.js to package up these templates, for me it looks like:
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyWebpackPlugin([
'./templates/*'
])
]
};
fs.readFileSync cannot find file when deploying with lambda
Check the current directory and check target directory content in deploy environment. Add appropriate code for that checking to your program/script.

Angular 2 - how to fill a local variable with JSON data from an external file

The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.
import {Component} from 'angular2/core';
import {Foo} from './foo';
#Component({
etc.
});
export class AppComponent {
bar = BAR;
}
var BAR: Foo[] = [
{ 'id': 1 },
{ 'id': 2 }
];
However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?
Create a file with this content
export const BAR= [
{ 'id': 1 },
{ 'id': 2 }
];
save it as BarConfig.ts or some like
later use it as follows
import { BAR } from './BarConfig';
let bar= BAR;
or even better, use BAR directly where you needed
HTTP_PROVIDER is needed if you want to load a file using http.
Here is an example of how to load a local json file over http:
this.result = {friends:[]};
this.http.get('./friends.json').map((res: Response) => res.json()).subscribe(res => this.result = res);
More details here: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
Juste put your .json file in your static folder (/assets if you are using the angular cli) and it should work.
Best option is to create json file and store json details inside file and call that file using like below.
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
You can use the Http provider in angular2
Make sure you place your local json file in the www folder.
getLocalFile(){
return this.http.get('./localFileName.json').
map(res => res.json());
}
This will return you the local JSON file.