I'm playing around with a React front-end for an app I want to build and I'm pretty new to React. I've been trying to run it with a Flask backend and have watched a variety of YouTube videos to guide me, but I've been stuck with this same issue for a couple hours now. I have a proxy pointing to my Flask backend, but the proxy never gets used.
Here is my setupProxy.js as instructed from the Create React App documentation:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
console.log("hello"); //extra print statement that never gets logged
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
Here is my get code that I stole from a video:
function App(){
const [data, setData] = useState(null);
function getData(){
axios({
method: "GET",
url: "/api",
})
.then((response) => {
const res = response.data;
setData(({
name : res.name,
age : res.age
}))
}).catch((error) => {
if(error.response){
console.log(error.response);
console.log(error.response.status);
console.log(error.response.headers);
}
})
}
...
I've updated my package.json and played around with different get calls, but they all seem to lead to the same issue. When I run my app, the setupProxy.js never seems to get run. The request is always sent to "http://localhost:3000/api" and I even have an extra console.log statement that never gets run. Am I missing something? Any help would be greatly appreciated. <3
Related
my api call isn't sending to the proxy url domain. I know that it isn't calling as the console.log in the server isn't going off. Could someone please help me?
//client package.json
"proxy":"http://localhost:3001"
//client app
useEffect(() => {
const apicall = async () => {
try{
const response = await fetch("/")
if (response.status !== 200){
throw new Error()
}
else{
console.log("api call was success")
console.log(response)
}
} catch(error){
console.log(error)
}}
apicall()
}, [])
//server
app.get("*", (req,res)=>{
console.log("apicalled")
res.cookie("refreshToken", 987654321, {
maxAge: 60000,
httpOnly: true
})
res.send("has cookie sent?")
})
Don't have an answer for you, but it looks like you're using create-react-app? I think if you've setup your own server, you don't need to set the proxy in your package.json.
I am running a small react app and trying to access an external api behind my company's proxies. I continue to get the cors error - I've tried setting a proxy in package.json and using setupProxy.js (separately), but haven't had any luck.
I have create api with Python (django restframework). I am calling that api from my react applicaation using redux.
It works fine when i call it like this
const {data} = await axios.get(`http://127.0.0.1:8000/api/products/${id}`)
but when i change the url to
const {data} = await axios.get(`api/products/${id}`)
It then makes a request to a different route ( http://localhost:3000/product/api/products/6) and I want it to make a call to (http://localhost:8000/api/products/6
I have added the path in django server and allowed calls from the react app. and it is working perfectly when i was working with other routes.
for example it was working fine when i was making call to this route
const {data} = await axios.get('api/products/')
You need to give the url to the api. If you don't provide full url, it will add your react app url.
You can declare a variable with the route
API_URL = "http://localhost:8000/"
const {data} = await axios.get(`${API_URL}api/products/${id}`)
module.exports = {
//...
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
},
},
},
};
Add the above configuration to your webpack,then the request can be forwarded by wepack dev server.
more details,please visit https://webpack.js.org/configuration/dev-server/#devserverproxy
Cannot retrieve data form MongoDB Atlas Back-end using mongoose and axios.
I have been using React hooks and calling the axios get inside my contextProvider after which I dispatch the data to the reducer.
I have tried most of the solutions I could find and none seemed to solve the issue. I have been stumbling from one error to the other without having any clue how to solve it.
here is the most frequent error:
Proxy error: Could not proxy request /api/projects from localhost:3000 to http://localhost:5001.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED).
I have read the nodejs documentation and understand the request was refused but it doesn't specify how to solve the problem
I would greatly appreciate any pointers
Here is the request:
const getProjects = async () =>{
try {
const res = await axios.get("api/projects");
dispatch({
type:GET_PROJECT_ALL,
payload:res
});
}catch(err){
console.log(err);
}
}
response:
GET /api/projects 304 69.326 ms - -
Here is the server set-up:
const dbURI = "mongodb+srv://My_Dev:****#*****.*****.mongodb.net/******?retryWrites=true&w=majority";
mongoose.connect(dbURI,{ useNewUrlParser: true, useUnifiedTopology: true}).then((result)=>{
console.log("connected to my mongodb")
app.listen(5001,()=>{console.log("connected on port 5001")});
}).catch((err)=> console.log(err.message));
app.use(express.json({extended:true }));
app.use(morgan('dev'));
// setting up cors
var corsOptions = {
origin: "http://localhost:5001"
};
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors(corsOptions));
// defining our routes:
// routes handling projects
app.use('/api/projects', require('./routes/projects'));
this is the handler:
router.get('/',async (req,res) => {
try{
const projects = await Project.find({private:false})
.sort({createdAt:-1})
.populate({path: 'collaborators',select:"memberName"})
.populate({path: 'roles',select:"roleName"});
res.send(projects);
}
catch (err){
console.error(err.message);
res.status(500).send('Server error');
}
})
this is how I access it within the react component :
const projectContext = useContext(ProjectContext);
const {projects, getProjects } = projectContext;
useEffect(() => {
getProjects()
console.log(projects.length);
});
if(projects.length === 0 ){
return <h3>there is nothign to be found ...</h3>
}
When starting nodemon and concurrently:
(node:13839) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
[0] connected to my mongodb
[0] connected on port 5001
[1] ℹ 「wds」: Project is running at http://192.168.1.23/
Tried all possible solution that I could find but there seemed to be an unidentifiable error that persisted where multiple ports kept overriding each other.
I finally solved it by using the archaic yet always reliable method of turning the computer off and back on.
I know it's not the technical answer some might have expected but I hope it will help people consider this option sooner rather than later in the process of resolving a similar issue.
I am running a React app with an Express server back-end on port:5000. I am making a request to one of my endpoint using the state of the element to get some data and then render it to the page. I initially setup the proxy in the package.json file of the React app as "proxy": "http://localhost:5000" (documentation. Now it was giving me a proxy error saying cannot proxy to localhost:5000. So I used CORS in my express server as a universal middleware for all of the routes using app.use(cors()).That removed the proxy error but the request is still not working (the code is not even reaching the endpoint because nothing is being logged to the console) and I am pretty sure it's because of the same error. Here are the code snippets
router.get("/", async (req, res) => {
var elements = [];
elements = await Element.find();
res.json(elements);
});
const getElements = async () => {
try {
console.log('getElements call')
const data = await axios.get("/api/elements");
console.log(data);
dispatch({ type: GET_ELEMENTS, payload: data });
} catch (e) {
console.error(e);
}
};
const { getElements, elements, loading } = elementContext;
useEffect(() => {
getElements();
}, [])
Expected behaviour: I want the endpoint to send an array name elements to the call which can then be set to the elements state using the reducer and then can be accessed by destructing in the end. I hope I have given adequate information. Any help will be appreciated. Thank you.
I'm not sure how to log / see the actual request that is being made.
I can look at this code below and assume that it's http://myendpoint.com?my/path?param=value, however with more complex code and variables in other places, how can I tell what exactly is getting called via API.get?
The main reason I ask is because I don't think my query parameters are being appended to my request, and I'm hoping to confirm.
const apiName = 'http://myendpoint.com'
const path = '/my/path'
const myInit = {
queryStringParameters: {
param: 'value'
}
}
API.get(apiName, path, myInit)
.then((response) => {
console.log('> > > PLEASE TELL ME HOW TO LOG THE REQUEST < < <')
resolve(response)
},
(err) => {
console.log('err resp', err)
resolve(err)
})
Edit: FYI this is in a REACT NATIVE project, so things like the Chrome Network tab are of no use unfortunately.
Okay, I actually think I figured this out, and it boiled down to two different things:
1. ADDING THE AMPLIFY LOGGER:
I found there is an Amplify logger via:
https://github.com/aws/aws-amplify/blob/master/media/logger_guide.md
So I added:
Amplify.Logger.LOG_LEVEL = 'DEBUG'
and now when I am debugging in VS Code I'm seeing the request URL being logged.
2. REALIZING 'queryStringParameters' ISN'T ACTUALLY SUPPORTED: .
I was looking through the Amplify GitHub repo issues and found out that queryStringParameters isn't actually supported yet, which is fun.
URL to issue: https://github.com/aws/aws-amplify/issues/127 .
So instead I appended all my query parameters onto the path, and that works:
const apiName = 'http://myendpoint.com'
const path = `/my/path?param=${value}`
API.get(apiName, path)
.then((response) => {
resolve(response)
},
(err) => {
console.log('err resp', err)
resolve(err)
})
I am now seeing the request URL logged, and seeing the parameters as a part of the request.