Calling image from nodejs in react js - node.js

I created a backend in node.js and a frontend in react.js. In the node app, I stored images in public/img folder but I can't access it in my react app
Node URL: http://127.0.0.1:8080
React URL: http://127.0.0.1:3000
The Cross-Origin-Resource-Policy header s set to same-origin. I wanna set it to cross-origin.
This is my cors code
app.use(
cors({
origin: process.env.FRONTEND_URL,
credentials: true
})
);
app.options("*", cors());
So how should I do it?

Related

Content Security frame-ancestors not working as expected

I have a react app running on http://localhost:5000/. Also I have another web app running on http://127.0.0.1:1880 and I want to open this website in iframe from react app. I set Content-Security-Policy: frame-ancestors http://localhost:5000/ but I'm still getting cors error and unable to see the content in iframe.
Node js code where I set the policies:
app.use(cors())
app.use(helmet({
contentSecurityPolicy: {
// "child-src": "http://localhost:5000",
directives:{
frameAncestors: "http://localhost:5000/",
}
}
}));
app.use(helmet.crossOriginEmbedderPolicy({ policy: "credentialless" }));
app.use(helmet.crossOriginOpenerPolicy({ policy: "unsafe-none" }));
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
Is there any way to fix this issue?

I want to set the port in the API from Heroku in React app

I am deploying Node and React app on Heroku at the same server, I have set up my Axios in React with base URL like this:
export default axios.create({
baseURL: `http://localhost:5001/api`,
withCredentials: true,
headers: {
"Content-type": "application/json",
},
});
Because Heroku creates a dynamic port for my Node app, this is not working to make request. Is there is any way I can read the port generated by Heroku and use it my React app?
If your app is deployed on heroku, why are you trying to use a url including localhost instead of the url of your app that heroku provides you?
Anyway, I think you can retrieve the port that heroku is using with process.env.PORT

Error occured while trying to proxy to: <ip>:3000/api/v1/metadata, react app host in aws

I have created react app with nodejs backend server. In my local machine (mac) this is working fine.
But when I host this app in aws ec2 server (ubuntu) , I'm getting this error when calling the backend apis.
Error occured while trying to proxy to: <ip>:3000/api/v1/metadata
I am using http-proxy-middleware to proxy requests for backend nodejs server.
src/setupProxy.js
const createProxyMiddleware = require('http-proxy-middleware')
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://127.0.0.1:5000',
changeOrigin: true,
})
)
}
inbound rules

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
}

Connecting front end and back end React / 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

Resources