localhost CORS error using Flask and React - reactjs

I am having some trouble with the development of my React app. On the client side, I'm using Axios to make the requests to the API (Flask).
The problem is that I frequently get a CORS error only when I send the request to the localhost API. I have the same API running in Heroku without any error.
API route = http://127.0.0.1:5000
Client route = http://localhost:3000/#/
Client code:
const endpoint = process.env.REACT_APP_ENDPOINT;
// Fetch API data
const [data, setData] = useState([{}]);
useEffect(() => {
axios.get(endpoint + "/api/rooms")
.then((data) => {
console.log("API endpoint data retrieved.");
if (data[200] !== "No Rooms") {
setData(data);
}
}).catch((err) => {
console.error(err.message);
console.log("No rooms retrieved from API endpoint.");
});
}, [endpoint]);
Server (Python) code:
import os
from flask import Flask
from flask_socketio import SocketIO
from flask_cors import CORS, cross_origin
from dotenv import load_dotenv
from app_modules.util.rooms import Rooms
load_dotenv()
app = Flask(__name__, static_folder="/client/build")
app.config['SECRET_KEY'] = os.getenv("app_key")
app.config['CORS_HEADERS'] = "Content-Type"
ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS")
cors = CORS(app, resources={"/*": {"origins": ALLOWED_ORIGINS}}, support_credentials=True)
socketio = SocketIO(app,
cors_allowed_origins=ALLOWED_ORIGINS,
logger=False,
engineio_logger=False,
cors_credentials=True)
rooms = Rooms()
#app.route('/api/rooms')
#cross_origin(supports_credentials=True)
def home():
return {"rooms": rooms.secure_api} if rooms.secure_api else {"200": "No Rooms"}
Note:
ALLOWED_ORIGINS=*
But I keep getting this error:

In your server code change
ALLOWED_ORIGINS = os.getenv("ALLOWED_ORIGINS")
to
ALLOWED_ORIGINS = ['localhost', '127.0.0.1']

Related

Cant do a proxy

Hey i have a express app with a api route
app.get("/api", (req, res) => {
res.json({ message: "Its work !! !! !" });
});
And i have a reactjs app with that in package.json
"proxy": "http://localhost:3001",
When i want to go on api route of express app (http://localhost:3001/api) its work but its not work with my reactjs app when i go on (http://localhost:4000/api)
i start my webserver with
yarn run clean && cross-env NODE_ENV=development webpack-dev-server --host localhost --hot --https
The problem can be a problem from react router dom?
Resolved Solution:
In webpack config add proxy to devserver
As you are proxying requests, you can access the API endpoints from within react application (proxy parses requests to API), but nevertheless your API is still on its server (or another port on localhost f.e.)
Your React app just proxies the request
Example how to query your data with proxy configured:
import { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [data, setData] = useState();
useEffect(() => {
const getData = async () => {
// you can use /api here as you proxi it to your API url
// f.e. localhost:5000/api
const response = await axios.get("/api");
setData(response.data);
};
getData();
}, []);
// stringify your data in json
return <pre>{JSON.stringify(data, undefined, 2)}</pre>;
};
export default App;

How to resolve get request with axios in React?

I'm new to Axios, and I was trying to fetch data from an endpoint to use in React...
import axios from "axios";
const api = axios.create({ baseURL: "http://localhost:5000/" });
export default function App() {
api.get("/products").then(res => console.log(res.data));
...
}
Here is my endpoint code...
const express = require("express");
const app = express();
require("dotenv").config();
app.get("/products", (req, res) => {
res.send("Hello world!");
});
const port = process.env.PORT;
app.listen(port, () => console.log(`Listening on port ${port}...`));
But instead of the Hello world! getting logged I am getting this error...
Any help would be appreciated.
Hi look for this lib Cors for express and you can use proxy in react project in your package.json instead of axios.create()
like
"proxy": "http://localhost:5000"
Install cors middleware in your backend server.
npm install cors
Enable all CORS requests
const express = require("express");
var cors = require('cors')
const app = express();
app.use(cors())
You can look for more information here. There are ways to configure your CORS as well.
To your another question, CRUD operations should be used in useEffect hook.
import React, { useEffect } from 'react';
export default function App() {
useEffect(() => {
api.get("/products").then(res => console.log(res.data));
}, [])
...
}

How can one deploy Apollo Server with Create-React-App?

I'm trying to deploy my application to a production environment, but having some trouble wiring it all together.
I've got a create-react-app for my frontend, which is served up by a simple express/serve server. On the backend, I've got NGINX proxying successfully to my API server, which is using Apollo to serve my data. The API is running on port 4000.
The Apollo-Server is as-follows, and works fine:
import { resolve } from "path";
import dotenv from "dotenv";
const envi = process.env.NODE_ENV;
dotenv.config({ path: resolve(__dirname, `../.${envi}.env`) });
import "reflect-metadata";
import { connect } from "./mongodb/connect";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import { SenateCommitteeResolver, HouseCommitteeResolver } from "./resolvers";
import { populateDatabase } from "./util";
(async () => {
// Connect to MongoDB
await connect();
console.log(`📊 Databases connected`);
const schema = await buildSchema({
resolvers: [HouseCommitteeResolver, SenateCommitteeResolver],
emitSchemaFile: resolve(__dirname, "schema.gql"),
});
// If development, set database docs
envi === "development" && (await populateDatabase());
// Launch the server!
const server = new ApolloServer({
schema,
playground: true,
});
// Server listens at URL
const { url } = await server.listen(4000);
console.log(`🚀 Server ready, at ${url}`);
})();
I'm trying to connect my express server to the Apollo Server, but that's where I'm running into problems. The application is supposed to connect using Apollo's Client and HTTP Link, because I'm using Apollo Client on the frontend too:
import React, { useEffect } from "react";
import { AppRouter } from "./routers";
import ReactGA from "react-ga";
import { ApolloProvider } from "#apollo/client";
import client from "./graphql/client";
import "./styles/index.scss";
function App(): React.ReactElement {
return (
<ApolloProvider client={client}>
<AppRouter />
</ApolloProvider>
);
}
export default App;
And here's the client file:
import { ApolloClient, InMemoryCache, createHttpLink } from "#apollo/client";
const httpLink = createHttpLink({ uri: process.env.REACT_APP_API as string });
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
connectToDevTools: true,
});
export default client;
However, when the user navigates to the site and the site itself tries to make a request to my backend, I'm getting a CORS error:
Access to fetch at 'https://www.cloture.app/' from origin 'https://cloture.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
What's going wrong? How can I connect Apollo's client with my Apollo Server on the backend?
Adding it here, because the suggestion requires some code.
Try adding :
const server = new ApolloServer({
schema,
playground: true,
cors: {
origin: "*" // it will allow any client to access the server, but you can add specific url also
}
});

React js and Mongodb web application getting error?

Proxy error: Could not proxy request /api/games from localhost:3000 to http://localhost:8080/ (ECONNREFUSED).
code in action.js (Redux)
export function fetchGames(){
return dispatch =>{
fetch('/api/games')
}
}
import express from 'express';
import mongodb from 'mongodb';
const app = express();
const dbUrl = 'mongodb://onkar localhost:27017/crudwithredux';
mongodb.MongoClient.connect(dbUrl, function(err, db) {
app.get('/api/games', (req, res) => {
db.collection('games').find({}).toArray((err, games) => {
res.json({ games });
});
});
app.listen(8080, () => console.log('Server is running on localhost:8080'));
});
** Hi i m onkar, I am new in react js. i getting error in server page. I have mongo db database so i m retrieve the data from mongo db. and show in Json format in react js using redux.**

Trying to make axios react request from localhost:8080 to a rails server localhost:3000

My rails server at localhost:3000 is serving this json:
and I'm trying to make a request from react like this:
import axios from 'axios'
export const ROOT_URL = 'localhost:3000';
export const FETCH_HANGOUTS = 'FETCH_HANGOUTS';
export function fetchHangouts() {
const path = 'api/v1/hangouts'
const url = `${ROOT_URL}/${path}`;
const request = axios.get(url);
console.log("url:", url)
console.log("request:", request);
return {
type: FETCH_HANGOUTS,
payload: request
};
}
But this is failing with this error:
[[PromiseValue]]: Error: Network Error at createError (http://localhost:8080/bundle.js:23880:16) at XMLHttpRequest.handleError (http://localhost:8080/bundle.js:23732:15)`
What is going on?
The problem you are facing for CORS error. You can't access to your server because of cross origin policy as a result you are getting network error.

Resources