Getting an error when trying to read json file via fetch - json

I am trying to read json file from local, but as a response I am getting an error look like this
Fetch API cannot load file:///var/www/desktop-electron//dashboard/bnb.json. URL scheme "file" is not supported
Here is my code
fetch(`${drr}/dashboard/bnb.json`)
.then(res => res.json())
.then(res => {
this.currency = res;
Object.assign(this.stock, res.pairs[0]);
Object.assign(this.header, res.pairs[0]);
this.header.name = res.name;
}).catch(function(e) { console.log(e) });
I have read all solutions which from google ,but can not solve the problem!

have you tried to omit the "file://" scheme altogether?
Also first try to wrap the URI in a Request Object, like described here
fetch(new Request(URI))

Native fetch (Chromium) doesn't support to load resources from local via file protocol. In short you can't, you need to use other way around (like fs.readfile, or some other means) or host json to remote endpoint to use fetch.

Related

Chrome extension, how to track each visited page?

I wanted to build a Google Chrome extension that would display domain popularity, the way Alexa domain stats did;
I am able to display any data inside popup.html when user clicks my extension button (to show domain rank, backlinks, etc) but in background I need to track popular urls visited by users.
Using manifest v3, I was able (inside background.js) to detect and trigger code on each url change, but I cannot find a function that would allow the extension to ping my servers in order to tell what url/domain is visited by user.
I assume best way to do this is to make an URL get request in background. How can I do something like that ? Basically I want the extension to send a text message to an url of mine.
As wOxxOm mentioned you can use built in fetch API. As mentioned in this documentation, you can use fetch like this -
fetch(your_url, fetchParams) //fetch returns promise, that resolves to a response object
.then(response => response.json()) //assuming JSON response
.then(data => console.log(data))
.catch(err => console.error(err));
where fetchParam is typically a javascript object that follows the documentation mentioned above. you can add your custom data in the fetchParam's body key. like this
fetchParam = {
method: your_metod,
headers: your_header_object,
body: your_data
};
Hope I understood the question correctly.

How can I send data (string) from my html to my server (node or express) and execute certain function with it?

I have a node.js server running and is executing what I want it to do, create an excel document with data fetched with Axios from an API, now, I want to allow a user to input a string on my HTML and then send that string to my web server, and perform an Axios request to the API that I am consuming. How can I do that? Should I use a POST request, a PUT request, or anything else?
Thanks!
You should be able to send data from your client to the server via the request body regardless of the request method whether GET/POST/PUT.
fetch call would look like this
// just a simple get request
fetch('/example-endpoint', {
method: 'POST',
body: {
data: 'String to be sent'
}
});
And on your node express server
app.post('/example-endpoint', (req, res) => {
const data = req.body.data;
// do stuff with your data here.
})
GET request method is used for getting data, while POST and PUT are used for creating and updating data, so use them as you need them.
POST request to your server, like uh https://myserver.com/api/${userString}
something like that

get json data from a public json file not REST api with React

I have a url similar to https://www.nonexistentsite.com/fubar.json where fubar.json is a public json file which will download to your file system if you navigate to the url with your browser. I have a React web app where I want to read that file directly so as to display some of its data. I don't want to bother with any kind of a backend that would download the file to the apps file system so that it can read it. I want the React front end to read it directly in it's client side code with a fetch or an axios call or something like that. I'm familiar with the typical situation where I have a REST url like https://www.nonexistentsite.com/fubar which I can call and get the data. I'm failing to find info on how to handle this situation.
You could use Axios to load the data from the json file.
Example usage;
axios.get('https://www.nonexistentsite.com/fubar.json')
.then(jsoncontent => {
console.log(jsoncontent);
//do stuff with jsoncontent here
});
Maybe I'm misunderstanding your question, but I believe if you are just needing to fetch the json from a hosted file, you should be able to do so with axios.get(url)

Superagent: Error: Parser is unable to parse the response

I'm using Superagent in my react app, and i'm making some call's to the IPFS api. Specifically, I am uploading files to my IPFS server. Now, everything works, When I upload one or multiple files the call goes through and the files show up in IPFS no problem.
A problem occurs when I upload multiple files though, the response seems to come back as plain text, instead of JSON, and superagent throws the error
client.js:399 Uncaught (in promise) Error: Parser is unable to parse the response
at Request.<anonymous> (client.js:399)
at Request.Emitter.emit (index.js:133)
at XMLHttpRequest.xhr.onreadystatechange (client.js:708)
So to be clear, when uploading a single file, I get a nice JSON response, but when I upload multiple files, the response is in plain text.
Can I force Superagent to give me the response back and parse it myself? Or can I set something when making the call so that it forces a json parse? Below is my superagent request function
add : acceptedFiles => {
const url = ipfs.getUrl("add")
const req = request.post(url)
acceptedFiles.forEach(file => req.attach(file.name, file))
req.then(res => {
return console.log(res);
})
}
I'm searching for this for a more elegant solution, but before I would have found it , I'd like to provide my own solution.
I think this problem caused by wrong responsive Content-Type set, but I've not confirmed this opinion yet.
However, you can try this:
req.catch(function (err) {
console.log(err.rawResponse)
})
At least, this solves my problem.
According to their docs you can specify custom parser that will take precedence over built-in parser:
You can set a custom parser (that takes precedence over built-in parsers) with the .buffer(true).parse(fn) method. If response buffering is not enabled (.buffer(false)) then the response event will be emitted without waiting for the body parser to finish, so response.body won't be available.
I tried and it worked well for me.
superagent.get('....')
.buffer(true)
.parse(({ text }) => JSON.parse(text))
.then(...)

Not able to use a fake back end server for angular 2 . Choosing in-memory-web-api is not working for me

I am building a fake back end server for my Angular2 application and I want to use for this purpose "angular2-in-memory-web-api". I have created the service for my http request and also a typescript file with createDb() method
I am following heroes demo of angular documentation and I do not understand what is the meaning of :
private heroesUrl = 'api/heroes'; // URL to web api . I do not find this file and I know it should be a json file
constructor(private http: Http) { }
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
In my application I have created the InMemoryDbService and all datas are inside createDb() method but also I have a json file in my api folder like api/products.
Now when I run the application I got the error "Collection not found". If I comment out the code about InMemoryWebApi I am able to retrieve all the products. I could have gone with the example of json file but I need to do also put, post, get(id:number) requests and I am not able to do it with the usage of json file.
I am wondering now win the Angular2 demos which can be found on https://angular.io/docs/ts/latest/tutorial/toh-pt6.html# I do not see any file on api/heroes.
Does it mean that this path does not exist, or if it exists is it an empty json file? I have tried to delete the json file, also just do it an empty file but still it is not working.
Note: The code is programmatically ok