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

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

Related

how to call expressjs endpoint from static html file in vercel

i have a very simple app with 1 /api/index.js server and 1 index.html file at the root.
index.js has a route app.get("/api/mystuff", () => {...})
index.html calls pings this route from a <script> with:
const result = await fetch("/api/mystuff")
all of this works locally, but when deployed to Vercel i get hit with a 404 from my request. the endpoint it's hitting is https://myvercelapp.vercel.app/api/mystuff and i'm getting a The page could not be found NOT_FOUND error. I don't know how to get this working, can someone steer me in the right direction?
thanks!
Based on the used tags I'm understanding you are using express with node.js.
Without seeing any of your code, I am guessing either your vercel.json isn't setup correctly (the guide explains this) or your index.js isn't setup correctly.
Vercel Guide on using Express
In that case, Vercel has a great guide on Using Express.js with Vercel.
In vercel's guide they have a section addressing using Standalone Express.
In this guide they use an index.js inside of an api folder.
The index.js file:
const app = require('express')();
const { v4 } = require('uuid');
app.get('/api', (req, res) => {
const path = `/api/item/${v4()}`;
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 's-max-age=1, stale-while-revalidate');
res.end(`Hello! Go to item: ${path}`);
});
app.get('/api/item/:slug', (req, res) => {
const { slug } = req.params;
res.end(`Item: ${slug}`);
});
module.exports = app;
and the vercel.json which is what makes the whole project work.
{
"rewrites": [{ "source": "/api/(.*)", "destination": "/api" }]
}
And finally, Adding a Public Directory which may explain more on how you can properly use Vercel with Express.
The Problem
The reason I assume that it's the vercel.json is the problem is due it working locally and not on Vercel. A good way to test this locally is using vercel dev.
Working Example
I've created a public example which may help you. Please check https://github.com/Crispy-Cream/vercel-with-express for the source code example
and the public website https://vercel-with-express.vercel.app/api

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!!

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

firebase serve and debugging functions?

I ran
firebase serve --only-functions
Then ran
functions inspect addMessage
So I could debug the addMessage function. Debugging however did not work.
Running
firebase deploy addMessage --trigger-http
firebase inspect addMessage
Did work and allow me to debug but it doesn't seem to support hot reloading.
Is it possible to have hot reloading and debugging working at the same time?
My index.js:
const functions = require('firebase-functions');
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();
exports.addMessage = functions.https.onRequest((req, res) => {
// Grab the text parameter.
const original = "123";//req.query.text;
// Push the new message into the Realtime Database using the Firebase Admin SDK.
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
// Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
return res.redirect(303, snapshot.ref.toString());
});
});
try: ndb firebase serve
debugger breakpoints are hit with stack traces visible, note it's a little slow so give the debugger time to instrument the child processes
Additionally I was able to debug cloud functions in isolation using (caps for removed values):
GCLOUD_PROJECT=THE-FIREBASE-PROJECT node --inspect-brk /path/to/functions-framework --target FUNCTION-NAME --port=5000
where functions-framework simply expands to the full path for the installed functions-framework (global in my case) from the working directory where the index.js file is for the target functions.
Alternately when or where the FIREBASE_CONFIG is needed try this format adjusted to fit:
FIREBASE_CONFIG="{\"databaseURL\":\"https://YOUR-FIREBASE-PROJECT.firebaseio.com\",\"storageBucket\":\"YOUR-FIREBASE-PROJECT.appspot.com\",\"projectId\":\"YOUR-FIREBASE-PROJECT\"}
https://github.com/GoogleChromeLabs/ndb
https://cloud.google.com/functions/docs/functions-framework
https://github.com/GoogleCloudPlatform/functions-framework-nodejs/issues/15
As of firebase-tools v7.11.0, the Firebase emulator now supports attaching a debugger with the --inspect-functions option. This answer shows WebStorm-specific instructions that can be easily adapted to other debuggers.

Loading weather API data into electron App

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();

Categories

Resources