如何从前端开发服务器react连接到后端服务器



我在8000端口上运行节点后端,在9002端口上运行开发服务器前端。在运行dev时,我尝试了几种代理到后端的方法,但似乎都失败了(也许是因为我也有

"type": "module")?我尝试过http代理中间件,但没有成功。

在我的server.js文件中,我有一个app.get('/properties'….(。它检索一个包含地址、城市和邮政编码的对象数组。在邮差上,我在8000端口上运行,得到了正确的回复。此外,当我在前端的8000端口上运行start时,我也会得到正确的响应。但是,当我在端口9002上运行时,我的错误是http://localhost:9002/properties404,未找到。

出于开发目的,我需要能够进行开发,这样我就不必为我所做的每一次UI更改都运行构建。下面是我的一些代码片段:

软件包.json


{
"name": "properties-three", 
"version": "1.0.0", 
"description": "",
"main": "index.js", 
"type": "module", 
"proxy": "http://localhost:8000", 
"scripts": 
{ 
"test": "echo "Error: no test specified" && exit 1", 
"dev": "webpack-dev-server --open --config webpack.config.cjs", 
"start": "nodemon --use_strict server.mjs", 
"build": "webpack --mode production" 
}, "
author": "", 
"license": "ISC", 
"devDependencies": { 
"@babel/core": "^7.19.6", 
"@babel/preset-env": "^7.19.4", 
"@babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5", 
"copy-webpack-plugin": "^11.0.0", 
"html-webpack-plugin": "^5.5.0", 
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0" 
}, 
"dependencies": { 
"axios": "^1.1.3", 
"cors": "^2.8.5", 
"express": "^4.18.2", 
"http-proxy-middleware": "^2.0.6",
"react": "^18.2.0", 
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.2", 
"webpack-dev-server": "^4.11.1" 
}
}

setupProxy.js

import {createProxyMiddleware} from "http-proxy-middleware";
module.exports = function(app) {
app.use(
'/api/properties',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
secure: false,
ws: true
})
);
};

webpack.config.js:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
const htmlPlugin = new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
entry: "./src/index.js",
output: { // NEW
path: path.resolve(__dirname, 'dist'),
filename: "bundle.js",
publicPath: "/"
}, // NEW Ends
devServer: {
port: 9002,
static: path.join(__dirname, 'dist'),
hot: true,
historyApiFallback: true
},
resolve: {
extensions: ['.ts', ".js", ".jsx"],
},
mode: "development",
plugins: [htmlPlugin],
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};

server.mjs

import express from 'express';
import cors from 'cors';
import path from "path";
import properties from './routes/properties.routes.js'
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 8000;
app.use(express.static(`${process.cwd()}/build`));
app.use(express.static(`${process.cwd()}/public`));
app.use(cors());
app.use(express.json());
app.use("/properties", properties);
app.use(express.static(path.join(__dirname, '/dist')));

app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

app.listen(PORT, () => console.log(`server is running on http://locahost:${PORT}`));

App.js

import React, {useState, useEffect} from "react";
import axios from "axios";
function App() {
const [properties, setProperties] = useState([]);
useEffect(() =>{
axios.get('/properties').then((response) =>{
setProperties(response.data)
})
}, []);
return (
<div className="App">Test</div>
);
}
export default App;

我已尝试将setupProxy.js更改为使用

import {createProxyMiddleware} from "http-proxy-middleware"; 

而不是

const { createProxyMiddleware } = require('http-proxy-middleware');

我也尝试过在组件中进行更改

axios.get('/properties') 

axios.get('/api/properties')

我找到了修复方法。正如@NirAlfasi所指出的,我在同一台机器上运行BE和FE。此外,我的数据库目前正在使用存储在我的项目中的模拟数据(在此期间(。

在我的App.js中,我所需要做的就是创建一个指向BE端口的const baseUrl。然后在FE上的get请求中,指向该baseUrl和端点。

const baseURL = 'http://localhost:8000';
axios.get(`${baseURL}/properties`).then((response)...

最新更新