我有一個應用程式在我的域上與 Express 中的服務器做出反應。該專案分為兩個部分(檔案夾),“前端”和“后端”。當我啟動 express 服務器時,它會在埠 4000 上進行偵聽,但是當 React 中的應用程式通過路徑 Ex:(" https://localhost.com/dataRequested")使用 axios 發出請求時,會出現 404 錯誤。當我將埠添加到偵聽服務器的域時,請求作業。例如:(“ https://localhost.com:4000/dataRequested”)
Index.js 服務器快遞
const routesHandler = require('./routes/handler.js');
const bodyParser = require('body-parser');
const https = require('https');
const fs = require('fs');
var privateKey = fs.readFileSync('sslcert/server.key', 'utf8');
var certificate = fs.readFileSync('sslcert/server.crt', 'utf8');
const credentials = {key: privateKey, cert: certificate};
const express = require('express');
const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use('/', routesHandler);
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(4000);
handler.js 路由服務器 Express
router.get('/randomElementsData', (req, res) =>
{
//functions
}
hero.js 組件 React 應用
const getHeroData = async () =>
{
try
{
const response = await axios.get('/randomElementsData');
setDataHero(response);
}
catch (error)
{
console.log(error);
}
}
uj5u.com熱心網友回復:
如果反應應用程式是獨立的,可能是 CORS 問題..
嘗試將此添加到快遞應用程式
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', `http://${process.env.HOST}:${process.env.PORT_CLIENT}`) // update to match the domain you will make the request from
res.header('Access-Control-Allow-Credentials', true)
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Auth-Token'
)
res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT')
if (req.method === 'OPTIONS') {
res.status(204).send()
} else {
next()
}
})
uj5u.com熱心網友回復:
將此添加到您的 package.json 檔案中
"proxy" : "http://localhost:4000"
react 使用它來將所有 fetch/axios 請求發送到節點服務器(僅在開發中)。然后節點服務器應該知道是將該請求轉發到 Reactjs 路由器還是快速路由器
我在所有 API 呼叫之前添加“/api”以幫助明確確定使用哪個路由器
app.use('/api', routesHandler);
// All other GET requests not handled before will return our React app
app.get("/*", (req, res) => {
res.sendFile(<the location of your build folder>);
// res.sendFile(path.join(__dirname, '/build'));
});
現在你的 axios 呼叫看起來像
axios.get('/api/randomElementsData')
uj5u.com熱心網友回復:
嘗試到達終點
http://localhost:4000/dataRequested
這甚至可能是因為 URL 無效
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/406242.html
標籤:
