Connecting front end and back end React / Node.js - node.js

I am trying to create an account through my registration form, however I keep on getting this error:
This is my registration form:
However when I press Register, get this error:
Commands: npm start
Errors: Proxy error: Could not proxy request /users/register from localhost:3000 to http://localhost:5000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
Error photo:
Much appreciated, thank you in advance.
Problem solved: Needed to start the React and the Node project on two different terminals, first run the React and then the Node project

Enable cors in your server
if Node and express
then add cors package and then in the entry point file ( index.js or app.js )
add this along with other imports
const cors = require('cors');
and then after your app is initialised then add this line
app.use(cors());
and also add these lines to the header of your request on the react side
'Access-Control-Allow-Origin': '*',
if you are using axios then I suggest you creating a separate file for axios
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:8000',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
});
there you configure your common axios details and import this file instead of the package wherever you using axios on react
If still facing an issue then please copy paste the error as it shows on the network tab

I think the solution to this is to run node server.js instead of npm start

Related

Cross-site POST form submissions are forbidden

My sveltekit app has a form which sends a POST request to server. The app is working fine on dev server but when I build and run the app it fails to send the form data via POST request. It shows the following error in the browser:
Cross-site POST form submissions are forbidden
You have to set the the ORIGIN env var like this
ORIGIN=http://localhost:3000 node build/index.js
https://github.com/sveltejs/kit/tree/master/packages/adapter-node#origin-protocol_header-and-host_header
This is a built-in protection against cross-site request forgery attacks in Sveltekit. Set csrf to false in svelte.config.js to allow cross-site post requests.
See csrf in the Sveltekit configuration docs
import adapter from '#sveltejs/adapter-node'
const config = {
kit: {
adapter: adapter(),
csrf: {
checkOrigin: false,
}
},
}
export default config
This works: node -r dotenv/config build after including your new variable in .env ORIGIN=https://yourwebsite.com (please install it with npm install dotenv command as pointed out here)

How do I proxy requests for static files on my node server to my react development server?

I have a node.js server that serves the built static files of my create-react-app at /admin. The problem is that anytime I make a change to my react app I have to build the files over again to see the updates. Instead, I'd like to proxy requests for my frontend at /admin to my dev server that comes with create-react-app, running at localhost:3000, because this would allow for a much faster development experience.
This is what my server looks like now:
// app.ts
...
const app: Koa = new Koa();
app.use(mount('/admin', serve(__dirname + '/build')));
...
And this is what I tried:
import proxy from 'koa-better-http-proxy';
const app: Koa = new Koa();
app.use(
mount(
'/admin',
proxy('localhost:3000', {})
)
)
What ends up happening is the requests for static files still go out and the response gives an index.html file but the JS doesn't seem to run and it gives me errors:
Uncaught SyntaxError: Unexpected token '<'
I've also played around with the proxy header settings to adjust content-type to application/json but I had no success there either.
Due to the environment, I cannot just run the node server in one terminal and the react app in another. The request comes from a verified 3rd party and must go through my node server first before being served the frontend portion of my app.

Connect node.js PostgreSQL database and Vue client locally

New to all of this so this might be the wrong setup. I have set up one project which uses node to connect to a postgreSQL. This works and I can start this from VS Code using:
node index.js
and the response is:
App running on port 3000.
Another project is a client and has been created Vue. This is started using
npm run serve
The response is:
App running at:
- Local: http://localhost:8080/
The Vue client gets data from a source using the code below and then displays it. In this example it uses some dummy data and works fine.
created: function () {
axios
.get('https://jsonplaceholder.typicode.com/users/')
.then(res => {
this.users = res.data;
})
}
However if I change the source above to communicate with the local postgreSQL database server:
.get('http://localhost:3000/users/')
I quite rightly get the security issue in the browser console when trying to connect:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:3000/users/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing)
So how do I intergrate the node.js part and the vue client part?
UPDATE
The answer to the question is below but I changed very slightly. The following was added to the index.js file (the node postgreSQL part). It is importing cors and saying allow conneciton from localhost:8080. Works perfectly:
import cors from 'cors';
const corsOptions = {
origin: 'http://localhost:8080'
};
You have to install lib cors. For that in your project folder just run the command:
npm i --save cors
After that lib is installed you should import and configure in your server application. To enable your front-end communicate with server side application.
const express = require('express');
const logger = require('morgan');
const cors = require('cors'); //<--install this lib
const app = express();
cors({ credentials: true, origin: true });//enable some headers for handling authentication tokens
app.use(cors());//use in your server
app.use(express.json());
if (process.env.NODE_ENV !== 'test') { app.use(logger('dev')); }
app.use(require('./server/index'));
module.exports = app;
As stated by the documentation, when you use the function cors() its equivallent to:
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}

How do I connect React native app with node js?

I have already created backend using node js for sigin & signup page. Now I want to connect to node js . But i have no idea how to do that. I want to connect both react native with my node js. Can you help me ?
simply as how we do for web apps.
here is an example of error reporting
export default async function (body) {
console.log(JSON.stringify(body))
const res = await fetch(`${host}/api/report`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
},
})
const { message } = await res.json()
if (message) return Toast({ message: message });
else return Toast({ message: 'network error' });
}
I have used fetch to send a POST request to my nodejs server
use API tool like postman or other and make your your nodejs APIs works fine and then connect to your React Native app as above.
You can use ngrok to connect Node with react-native. Run this command:
npm i ngrok -g # installing it globally
Then open another terminal. Run:
ngrok http 3000 # the port you are running on node
Then it will show an alternative link that you can use to test with your Node.
Note: if ngrok http 3000 doesn't work, try ngrok http -region us 3000.
The available ones are us, eu, ap, and au. In my case eu worked for me.
Then copy the link generated e.g. http://8074-129-205-124-100.eu.ngrok.io and test your backend if it displays APIs.
If the link works then you can use it with fetch. Uploading json data to send to MongoDB as the case maybe.

Angular 5 call api with CORS

Hello i am creating an Angular application that i need to call an API. I have run into the CORS Error. "No Access-Control-Allow-Origin" which I have found a few things on line about but I still do not understand where I am supposed to add the middlewhere. I wonder if someone could be specific on how to get this to work with angular cli.
If you open a command prompt and type ng new test then open that test folder up and type npm start. you add the code to call an api lets say localhost/someapi/api/people but because you're not calling localhost:4200 you get this error.
So just so that my question is clear, I understand that you need to add the cors middle where on the server. But the question is, where in the angular 5 app do I add this for node to read it and allow this to work?
Below is the code that I'm using to call api.
getToken():void{
let headers = new Headers({'Content-type': 'application/x-www-form-urlencoded'})
let params = new URLSearchParams();
params.append('username','some-username');
params.append('password', 'some-encripted-password');
params.append('grant_type', 'password');
let options = new RequestOptions();
options.headers = headers;
this.http
.post(this.appConfig.baseRoute + 'token',params.toString(), options)
.subscribe(result=>{ });
}
CORS headers should be set in server-side as per the answer in the link that you provided. There shouldn't be anything to set on the Angular client side other than maybe authentication tokens if you server requires them.
To ease your development locally, you could set up a proxy for ng serve.
Add this file in your root (folder with angular-cli.json)
proxy.conf.js
const PROXY_CONFIG = [
{
context: [
// what routes to proxy
"/api",
],
// your backend api server
target: "http://localhost:8000",
secure: false
}
]
module.exports = PROXY_CONFIG;
instead of calling ng serve, use ng serve --proxy-config proxy.conf.js

Resources