Loading weather API data into electron App - javascript

I started a project with my raspberry pi running an electron App where I need to get the actual weather from an open weather API. I am totally new to electron and not that experienced in Javascript. So I am stuck with getting the Data from the weather API into the App. I can request the Data as JSON or XML data. I tried out different ways I thought it might work but they all failed. So could someone tell me how to get API Data into electron in general?

The easiest way to start with API requests is to use axios.
After setting up the project (you can follow Getting Started), follow these steps:
Install Axios npm install --save axios
Create main.js in your project's folder.
Load main.js inside index.html somewhere before </body>.
Put the JavaScript code inside main.js
const axios = require('axios');
function fetchData() {
// you might need the next line, depending on your API provider.
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.post('api.example.com', {/* here you can pass any parameters you want */})
.then((response) => {
// Here you can handle the API response
// Maybe you want to add to your HTML via JavaScript?
console.log(response);
})
.catch((error) => {
console.error(error);
});
}
// call the function to start executing it when the page loads inside Electron.
fetchData();

Related

How to link React Native (expo) app with Nest js?

After setting the nest js project and verifying all routes using insomnia
I've tried enabling cors
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors()
await app.listen(3001);
}
bootstrap();
but I still get Network Error
the problem seems like from the Nest js project (cors specifically)
because I tryied linking the same nest js project with react js project and everything was going fine .
Otherwise,in react native when trying something like
const res = await axios.get("https://www.google.com/")
.then(res => console.log(res.data))
.catch(err => console.error(err));
i get all the data in the log
Try to use instead of the local address http://localhost:3001 your local IP address like: http://192.168.xxx.xxx:3001
try this link https://docs.nestjs.com/security/cors
it gives more ways to activate cors

ServerRuntimeConfig is empty

I am working on my nextjs project under docker, and when using getStaticProps my backend api is not available(which is also under docker). So I connected frontend to backend via networks and if i hardcode api for ssr request it works. But when i try to utilize serverRuntimeConfig and publicRuntimeConfig so i could switch between them depending on where code is being ran I get {} for serverRuntimeConfig. However publicRuntimeConfig is fine and i can access api from it.
My next.config.js is:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
baseUrl: 'http://localhost/api/v1',
},
serverRuntimeConfig: {
// Will only be available on the server side
baseUrl: 'http://backend_nginx_1/api/v1/',
},
am I missing something ?
This will sound dumb, but I spent 2 hours seeing the empty file been recognized by the system and just seeing {}.
Now... restarting the server, gives you access to the content of the file.
That was my solution.
And it was not included in the documentation.
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

How to fetch() from public folder in NextJS?

I've got following use case scenario. I have web worker within which I need to fetch image that is located in NextJS public folder in order to convert it to blob.
Right now executing fetch('public/images/myImage.png'); or fetch('/images/myImage.png'); leads to an error:
Error: TypeError: Failed to execute 'fetch' on 'WorkerGlobalScope':
Failed to parse URL from /images/ui/background_fire.jpg
So I assume it is not being resolved correctly like it would in say src of an image?
#NasiruddinSaiyed answer is a bit outdated so here is the 2021 answer:
NextJS server-side-polyfills docs
Server-Side Polyfills
In addition to fetch() on the client side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() on your server code (such as getStaticProps) without using polyfills such as isomorphic-unfetch or node-fetch.
So it should just work out of the box
As per official Docs you need to use isomorphic-unfetch.
It's a simple implementation of the browser fetch API, but works both in client and server environments.
Install it
$npm install --save isomorphic-unfetch
or
$yarn add isomorphic-unfetch
Now you can use it in from getInitialProps to any where in your component.
Example ::
`import fetch from 'isomorphic-unfetch';`
// ... Index component code
Index.getInitialProps = async function() {
const res = await fetch('https://api.tvmaze.com/search/shows?q=batman');
const data = await res.json();
console.log(`Show data fetched. Count: ${data.length}`);
return {
shows: data.map(entry => entry.show)
};
};
Happy coding!!

Load local file using Netlify functions

I've written a script which takes a JSON file and outputs it to an API endpoint using Netlify's Functions feature (https://functions.netlify.com/). For the most part, this works without a hitch, however, one of my endpoints has a lot of text and for ease of editing, I've split the large text blocks into markdown files which I then loaded into the endpoint.
Locally, this works perfectly, but when deployed I get a console error saying Failed to load resource: the server responded with a status of 502 (). I presume this is because I used a node fs method and Netlify doesn't allow that, however, I can't find any information about this.
The code I've used is here:
const marked = require('marked')
const clone = require('lodash').cloneDeep
const fs = require('fs')
const resolve = require('path').resolve
const data = require('../data/json/segments.json')
// Clone the object
const mutatedData = clone(data)
// Mutate the cloned object
mutatedData.map(item => {
if (item.content) {
const file = fs.readFileSync(resolve(`./src/data/markdown/${item.content}`), 'utf-8')
item.content = marked(file)
}
})
exports.handler = function(event, context, callback) {
callback(null, {
statusCode: 200,
body: JSON.stringify({data: mutatedData})
});
}
I've also attempted to replace
const file = fs.readFileSync(resolve(`./src/data/markdown/${item.content}`), 'utf-8')
with
const file = require(`../data/markdown/${item.content}`)
but that complains about a loader and I'd like to avoid adding webpack configs if possible as I'm using create-react-app, besides, I doubt it will help as I'd still be accessing the file-system after build time.
Has anyone else come across this issue before?
At the time when this answer is written (September 2019), Netlify does not seem to upload auxiliary files to AWS Lambda, it appears that only the script where the handler is exported will be uploaded. Even if you have multiple scripts exporting multiple handlers, Netlify seems to upload them into isolated "containers" (different AWS instances), which means the scripts will not be able to see each other in relative paths. Disclaimer: I only tested with a free account and there could be settings that I'm not aware of.
Workaround:
For auxiliary scripts, make them into NPM packages, add into package.json and require them in your main script. They will be installed and made available to use.
For static files, you can host them on Netlify just like before you have AWS Lambda, and make http requests to fetch the files in your main script.

Issues connecting to my Node.js and MongoDB backend using a React and axios front end

I am struggling currently when making a call using Axios to my backend, I currently have a user register page and I want to send the user data to the backend, everything seems to be set up correctly but I get these errors inside of my google chrome.
Here is the code from my React Register.js that breaks my program and causes this error.
onSubmit(e) {
e.preventDefault();
const newUser = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
password2: this.state.password2
};
axios.post('api/users/register', newUser) //EDIT : Line 35, where the error is
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
The onSubmit is connected to a button at the bottom of the website and all the code there is %100 fine. One issue that might be hurting me here is that my server is on localhost5000 while my front end is running on localhost3000 on my computer. I don't know how to fix this or what to do next, I've looked everywhere and this small issue is incredibyly frustrating.
Any help , pointers or general advice would be greatly appreciated as this seems like an extremely trivial error. Thanks in advance for any help.
Also look into the create-react-app docs to setup a proxy. CRA Proxy Docs
I like to setup my proxies in package.json (for the react client). I usually add the following, and all my routes start with api, to save on typing.
// somewhere in package.json
"proxy": {
"/api/*": {
"target": "http://localhost:5000"
}
}
If I was still getting a CORS error I would install the npm package cors (on the express app) and set that up as a middleware before my route handlers. Cors Docs
const app = express()
app.use(cors())
That is the most basic config, but you can specifically whitelist your front end if you want to.
app.use(cors({ origin: 'http://localhost:3000' }))
You can also add cors to any one route if you want to, in the usual express manner.
app.post('/api/user/register', cors(), (req,res) => {
// route handler
})
This is how I setup my apps using CRA and Express for development. Then when things go to production I don't have to change the api routes on the front end. That is the inherent problem with writing out the whole path ei: 'http://localhost:5000/api/users/register' - that is not going to work when the app goes to production say on Heroku, or wherever, and localhost:5000 is no longer the backend url. You would have to go back to all api routes and adjust them or insert ternaries for process.env.NODE_ENV, which is more work.
In this case all you need on the front end is axios.post('/api/users/register', newUser)
The proxy will take care of the rest in development.
Now when you publish site, if you chose to make it one single express app that serves your build statically, you just put the api route handlers above a catch all for serving the index.html. Anyways, this is a little beyond your question, just trying to give you an idea of one approach that will work down the line a little easier.
The issue is that when you run axios.post('api/users/register', newUser) it is running simply against http://localhost. You stated that the backend is running at http://localhost:5000 so you would want to run an absolute address to hit the backend properly. The code would turn into axios.post('http://localhost:5000/api/users/register', newUser) to hit the backend APIs.
Make sure you have "proxy": "http://localhost:5000" in your Client/React Package.json

Categories

Resources