问题
I am trying to connect my react frontend to the backend i tried everything but its still not working. I added "proxy" : "localhost:5000"
and no luck. I tried
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
and also no luck. Has anyone found a solution to the problem. I looked all over stackoverflow
UPDATE : Index file
// Imports
const express = require('express')
const app = express();
const cors = require('cors')
const mongoose = require('mongoose');
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const config = require('./config/key')
const routes = require('./routes/api')
require('dotenv').config()
// -----Connect to the database
mongoose.connect(config.mongoURI,
{useNewUrlParser: true,useUnifiedTopology:true,
createIndexes : true}).then(()=>{
console.log("Database connected")
}).catch((error)=>{
console.log(error)
})
// ----setting up middleware
const corsOptions = {
origin:['http://localhost:3000'],
credentials: true,
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))
app.use(bodyParser.urlencoded({extended : true}))
app.use(bodyParser.json())
app.use(cookieParser())
app.use('/api', routes);
// ---- Setting up server to listen on port 5000
app.listen(5000,()=>{
console.log("App is running on 5000")
})
回答1:
Update your code to this
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
app.use(
createProxyMiddleware("/api/*", { target: "http://localhost:5000/" })
);
};
回答2:
The problem for me was the port. It was set to 5432, after changing to 3002 worked again. Don't know why though, because if the port was already being used node should throw an error.
来源:https://stackoverflow.com/questions/62227839/react-proxy-error-could-not-proxy-request-api-from-localhost3000-to-http