I try to fetch a local json file in my project.
Tried the following:
import axios from 'axios';
import userDataJson from './../data/userData.json';
export const userDataControllerMixin = {
data() {
return {
users: [],
};
},
mounted() {
this.getUsers();
},
methods: {
getUsers() {
// TODO: load userObj.json initial to prevent reset the userData.json all the time
fetch(userDataJson)
.then((response) => {
console.log(response);
}).catch((err) => {
console.log(err);
});
};
i also tried it with axios before but they all lead into this error msg:
GET http://localhost:9080/[object%20Object] 404 (Not Found)
What am i doing wrong? Looks like a config issue.
You dont need to call fetch method anymore since you are importing your json data from the file. What you can do is, since you are already importing the json data, then when the component is mounted just assign the json data to the user array:
data() {
return {
users: [],
};
},
mounted() {
this.users = JSON.parse(userDataJson)
},
....
}
Related
I'm currently using axios and NextJS.
I currently have this code in my component:
export async function getServerSideProps(context) {
const data = await getVideo(context.query.id);
console.log('data: ', data);
// console.log('context: ', context);
console.log('context params: ', context.params);
console.log('context query: ', context.query);
if (!data) {
return { notFound: true };
}
return {
props: {
videoId: context.params.id,
videoSlug: context.params.slug,
videoContent: data
}
};
}
This getserverSideProps call the function of getVideo which looks exactly like this:
export const getVideo = (id) => async (dispatch) => {
dispatch({ type: CLEAR_VIDEO });
try {
console.log('Action file: ', id);
const res = await api.get(`/videos/${id}`);
return dispatch({
type: GET_VIDEO,
payload: res.data
});
} catch (err) {
dispatch({
type: VIDEO_ERROR,
payload: { msg: err.response?.statusText, status: err.response?.status }
});
}
};
Said function goes through my api function to make requests to backend:
import axios from 'axios';
import { LOGOUT } from '../actions/types';
import { API_URL } from '../config';
const api = axios.create({
baseURL: `${API_URL}/api/v1`,
headers: {
'Content-Type': `application/json`
}
});
/**
intercept any error responses from the api
and check if the token is no longer valid.
ie. Token has expired
logout the user if the token has expired
**/
api.interceptors.response.use(
(res) => {
res;
console.log('Res: ', res.data);
},
(err) => {
if (err?.response?.status === 401) {
typeof window !== 'undefined' &&
window.__NEXT_REDUX_WRAPPER_STORE__.dispatch({ type: LOGOUT });
}
return Promise.reject(err);
}
);
export default api;
It works great when doing POST, PUT,PATCH requests.
As you can see, I'm doing a console.log('data: ',data) but it returns [AsyncFunction (anonymous)] whenever I read the terminal; on the other hand, the front-end returns this error:
Server Error Error: Error serializing .videoContent returned from
getServerSideProps in "/videos/[id]/[slug]". Reason: function
cannot be serialized as JSON. Please only return JSON serializable
data types.
Does anyone knows how to solve this?
NOTE: I'm using react-redux, redux and next-redux-wrapper.
That is because your getVideo function returns another function. The right way to call it would be:
const data = await getVideo(context.query.id)()//<- pass in the dispatch here
But you should not use redux in the backend like that. I think you can completely remove it.
export const getVideo async (id) => {
try {
console.log('Action file: ', id);
const res = await api.get(`/videos/${id}`);
return res.data
});
} catch (err) {
return { msg: err.response?.statusText, status: err.response?.status }
}
};
// call
const data = await getVideo(context.query.id)
I'm trying to create a service in an Angular project that retrieves CSV data from an API server and passes JSON to the component.
The console displays nice JSON data from the service, but the component displays much earlier Component data: UNKNOWN.
I use the csvtojson module to convert CSV to JSON
Component
getData(): any {
this.storeService.getData()
.subscribe(data => {
console.log('Component data: ', data);
}, error => {
console.log(error);
});
}
Service "storeService"
getData(): Observable<any> {
return this.httpClient
.get('http://llocalhost:3000/user/11', { responseType: 'text' as 'text' })
.pipe(
map((data) => {
csv({
noheader: true,
trim: true,
delimiter: ';'
})
.fromString(data)
.then(jsonData => {
// This is OK - I can see a JSON data
console.log('Service jsonData', jsonData);
// How to send this jsonData to component?
return jsonData;
})
})
)
}
Thanks for your help.
This issue can be resolved easily by creating a behaviorSubject and assigning the fetched data to that variable.
And when you need to access the data in your component. ts file, you can simply subscribe to the behaviorSubject and get the data.
Once subscribed, you can simply call this.storeService.getData(); and get the updated value automatically(because you have subscribed to the behaviorSubject, it will update the component on value change).
Update your Service "storeService" to the following
yourJsonData: BehaviorSubject<any> = new BehaviorSubject<any>(null);
getData(): Observable<any> {
// DO NOT RETURN HERE
this.httpClient
.get('http://llocalhost:3000/user/11', { responseType: 'text' as 'text' })
.pipe(
map((data) => {
csv({
noheader: true,
trim: true,
delimiter: ';'
})
.fromString(data)
.then(jsonData => {
// This is OK - I can see a JSON data
console.log('Service jsonData', jsonData);
// STORE THIS JSONDATA TO A BEHAVIOUR SUBJECT
this.yourJsonData = jsonData;
})
})
)
}
Now Update your Component.ts file to this....
getData(): any {
this.storeService.getData();
this.storeServiceVariable.yourJsonData.subscribe((data) => {
console.log('Component data: ', data);
});
}
Try Using:
Just return the data in the service and do your thing in the component as follows
Service.ts
getData(): Observable<any> {
return this.httpClient
.get('http://llocalhost:3000/user/11', { responseType: 'text' as 'text' });
}
Component.ts
getData(): any {
this.storeService.getData()
.subscribe(data => {
csv({
noheader: true,
trim: true,
delimiter: ';'
}).fromString(data).then(jsonData => {
// This is OK - I can see a JSON data
console.log('Service jsonData', jsonData);
});
}, error => {
console.log(error);
});
}
I think this will help you....
I try to create a redux-react app where the users can import an csv-file that later is stored in a database. Right now I am working on the frontend where I want to create a code where the user can chose a csv file from their computer that they want to download and then the file is sent to the backend. I have therfore used the csvReader to read the csv-file but I don't know how to send the data to the backend. I am using nestJS in the backend. I want to send the whole csv-file in one go but i dont know how to tackle the problem. I am a beginner :))) Do you know how to solve my problem?
I can't help you with react but maybe this NestJS part can help you. You can use multer to config your api and setting a store path.
Create multer options
// multer.ts
const excelMimeTypes = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/wps-office.xlsx',
'application/vnd.ms-excel',
];
export const multerOptions = {
fileFilter: (req: any, file: any, cb: any) => {
const mimeType = excelMimeTypes.find(im => im === file.mimetype);
if (mimeType) {
cb(null, true);
} else {
cb(new HttpException(`Unsupported file type ${extname(file.originalname)}`, HttpStatus.BAD_REQUEST), false);
}
},
storage: diskStorage({
destination: (req: any, file: any, cb: any) => {
const uploadPath = '/upload'; // use env var
if (!existsSync(uploadPath)) {
mkdirSync(uploadPath); // create if not exists
}
cb(null, uploadPath);
},
filename: (req: any, file: any, cb: any) => {
cb(null, file.originalname);
},
}),
};
Import multerOption recent created and use FileInterceptor and UploadedFile decorator to get the file.
#Post()
#UseInterceptors(FileInterceptor('file', multerOptions))
uploadFile(#UploadedFile() file) {
console.log(file) // call service or whathever to manage uploaded file.. handleFile in the example below..
}
Manage file (example) using xlsx library.
handleFile(file: any): Promise<any> {
return new Promise(async (resolve: (result: any) => void, reject: (reason: any) => void): Promise<void> => {
try {
const workbook = XLSX.readFile(`${uploadLocation}/${file.filename}`);
resolve(workbook.Sheets[sheetName]);
} catch (error) {
reject(error);
}
});
}
I hope it helps!
I have an API that provides me XML data, and i want to convert that XML data from the API into JSON. Can anyone help me wiht that problem?
I'm using Expo to creat a app. I tried to use nodemoduls, but when i tried that I alwas get an error "It failed because React Native does not include the Node standard library" The code belwo dosen't work
import { View, Text, ActivityIndicator } from 'react-native'
import { fetch } from "fetch";
const furl = 'https://skimap.org/Regions/view/346.xml';
const xmlToJson = require('xml-to-json-stream');
const parser = xmlToJson({attributeMode: true});
export default class RegionList extends PureComponent {
state = { regions: [] };
async componentWillMount() {
fetch(furl).then(response => parser.xmlToJson(response, (err,json)=>{
if(err){
console.log(err);
}
}))
.then( (response) => this.setState({regions: response}));
}
Try this:
import {Xml2Json} from 'react-native-xml-to-json';
fetch(furl).then(response =>
Xml2Json.toJson(response, data => {
console.log("Data = ", data);
}).then( (response) => this.setState({regions: data})
);
I am trying to make an API call in React to return JSON data but I am a bit confused on how to go about this. My API code, in a file API.js, looks like this:
import mockRequests from './requests.json'
export const getRequestsSync = () => mockRequests
export const getRequests = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(mockRequests), 500)
})
It is retrieving JSON data formatted like this:
{
"id": 1,
"title": "Request from Nancy",
"updated_at": "2015-08-15 12:27:01 -0600",
"created_at": "2015-08-12 08:27:01 -0600",
"status": "Denied"
}
Currently my code to make the API call looks like this:
import React from 'react'
const API = './Api.js'
const Requests = () => ''
export default Requests
I've looked at several examples and am still a bit confused by how to go about this. If anyone could point me in the right direction, it would be greatly appreciated.
EDIT: In most examples I've seen, fetch looks like the best way to go about it, though I'm struggling with the syntax
Here is a simple example using a live API (https://randomuser.me/)... It returns an array of objects like in your example:
import React from 'react';
class App extends React.Component {
state = { people: [], isLoading: true, error: null };
async componentDidMount() {
try {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
this.setState({ people: data.results, isLoading: false });
} catch (error) {
this.setState({ error: error.message, isLoading: false });
}
}
renderPerson = () => {
const { people, isLoading, error } = this.state;
if (error) {
return <div>{error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
return people.map(person => (
<div key={person.id.value}>
<img src={person.picture.medium} alt="avatar" />
<p>First Name: {person.name.first}</p>
<p> Last Name: {person.name.last}</p>
</div>
));
};
render() {
return <div>{this.renderPerson()}</div>;
}
}
export default App;
Does it make sense? Should be pretty straight forward...
Live Demo Here: https://jsfiddle.net/o2gwap6b/
You will want to do something like this:
var url = 'https://myAPI.example.com/myData';
fetch(url).then((response) => response.json())
.then(function(data) { /* do stuff with your JSON data */})
.catch((error) => console.log(error));
Mozilla has extremely good documentation on using fetch here that I highly recommend you read.
The data parameter in the second .then will be an object parsed from the JSON response you got and you can access properties on it by just using the property label as was in the JSON. For example data.title would be "Request from Nancy".
If you are struggling with fetch, Axios has a much simpler API to work with.
Try this in your API.js file (of course install axios first with npm i --save axios):
import axios from 'axios'
import mockRequests from './requests.json'
export const getRequests = (url) => {
if (url) {
return axios.get(url).then(res => res.data)
}
return new Promise((resolve, reject) => { // you need to return the promise
setTimeout(() => resolve(mockRequests), 500)
})
})
In your component, you can access the getRequests function like so
import React, { Component } from 'react'
import { getRequests } from './API.js'
class App extends Component {
state = {
data: null
}
componentWillMount() {
getRequests('http://somedomain.com/coolstuff.json').then(data => {
console.log(data)
this.setState({ data })
})
}
render() {
if (!this.state.data) return null
return (
<div className='App'>
{this.state.data.title}
</div>
)
}
}
export default App