我正在嘗試將我的前端連接到我的后端,并且我正在使用帶有節點的快速服務器并做出反應。
這是我的前端獲取請求:服務器在埠 5000 上運行
const response = await axios.post("http://localhost:5000/send-email", {
to_email: data.data.email,
url: data.data.url,
});
console.log(response);
這導致:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/send-email. (Reason: CORS request did not succeed). Status code: (null).
我的后端有:
app.post("/send-email", async (req, res) => {
try {
const { to_email, url } = req.body;
console.log(to_email, url);
await sendMail()
.then((result) => console.log("Email sent...", result))
.catch((error) => console.log(error.message));
res.send({ express: "YOUR EXPRESS BACKEND IS CONNECTED TO REACT" });
} catch (error) {
console.log(error);
res.status(500).json({ message: error });
}
});
我也在使用核心,還有類似的東西:
// app.use(function (req, res, next) {
// // res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Origin", "http://localhost:3000");
// res.header(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept"
// );
// res.header("Access-Control-Allow-Methods", "POST, OPTIONS");
// res.header("Access-Control-Allow-Credentials", true);
// next();
// });
但考慮到更少,我不斷收到這個錯誤,我不知道如何擺脫它。我見過幾種解決方案,它們要么很舊,而且我嘗試了其中的一些,但它們根本不起作用。
uj5u.com熱心網友回復:
- 使用 (
npm install cors)安裝 cors 。 - 在您的后端代碼檔案中,添加
var cors = require('cors') <br /> app.use(cors())
或者,按照https://www.npmjs.com/package/cors給出的說明進行操作。
uj5u.com熱心網友回復:
一種方法是在你的 React 應用程式中使用代理。
您可以通過將此行添加到您的package.json檔案中來實作這一點:"proxy": "http://localhost:8000"這對開發來說很好。所以你的 package.json 看起來像這樣create-react-app:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
// use correct port of your localhost API
// and pay attention that there is no slash behind the port
// if you use slash in your app like this: /api
"proxy": "http://localhost:8000",
在您的反應應用程式中,您現在可以 POST 到您的端點/send-mail。如package.json已更改,需要重新啟動應用程式
const response = await axios.post("/send-email", {
to_email: data.data.email,
url: data.data.url,
});
如果這不夠靈活,也可以使用 package 手動添加代理http-proxy-middleware。為此src/setupProxy.js需要使用以下代碼創建,另請參閱此處的檔案create-react-app
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
package.json 中帶有代理的完整示例
前端反應
在 http://localhost:3000 上運行將用于演示目的的硬編碼資料發送到后端。我的服務器在埠 8000 上運行,所以我在 package.json 中使用:“proxy”:“http://localhost:8000”:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8000",
import axios from "axios";
const App = () => {
const postToBackend = async () => {
const res = await axios.post("/send-mail", {
to_email: "[email protected]",
url: "test-uri",
});
console.log(res.data);
};
return <button onClick={() => postToBackend()}>send to backend</button>;
};
export default App;
后端 Node.js
在 http://localhost:8000 上運行從反應前端和控制臺讀取傳入的資料。記錄資料。我的檔案夾結構:
├── app.js
└── routes
└── api
└── test.js
test.js Route 該路由將決議請求正文,列印并回傳狀態為 200。
const express = require("express");
const router = express.Router();
router.post("/", async (req, res) => {
const { to_email, url } = req.body;
try {
// this will print the test-email and test-uri hard coded in frontend
console.log(to_email, url);
// return values with status 200
res
.status(200)
.json({ message: `Incoming data is ${to_email} and ${url}` });
} catch (error) {
res.status(400).json({ message: error.message });
}
});
module.exports = router;
應用程式.js
在 app.js 中只需注冊路由,在我的情況下,我這樣做:
const express = require("express");
// express app
const app = express();
app.use(express.json());
// tell express to use /send-mail as endpoint for
// above route (stored in folder routes/api/test.js
app.use("/send-mail", require("./routes/api/test"));
// run server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
就是這樣,您應該能夠將資料從前端發送到后端。
uj5u.com熱心網友回復:
將您的 package.json 檔案中的代理添加到后端 api 的埠
"proxy": "http://localhost:8000"
然后將請求中的 url 更改為埠 3000 或前端所在的任何位置
const response = await axios.post("http://localhost:3000/send-email", {
to_email: data.data.email,
url: data.data.url,
});
console.log(response);
代理僅在本地作業,但是您的應用程式和 api 通常共享相同的主域,因此此 cors 錯誤不會出現在生產中..
uj5u.com熱心網友回復:
我將其修復如下:在我的前端,我有
const response = await axios.post("http://localhost:8000/signup", {
newUserNameEmail,
url,
});
console.log("response--> ", response.data);
在我的后端服務器中:
const PORT = 8000;
const express = require("express");
const cors = require("cors");
const nodemailer = require("nodemailer");
const { google } = require("googleapis");
const app = express();
app.use(cors());
app.use(express.json());
//sign up
app.post("/signup", async (req, res) => {
try {
const { newUserNameEmail, url } = req.body;
console.log(newUserNameEmail, url);
await sendMail(newUserNameEmail, url)
.then((result) => console.log("Email sent...", result))
.catch((error) => console.log(error.message));
res.status(200).json({ newUserNameEmail, url });
} catch (error) {
console.log(error);
res.status(500).json({ message: error });
}
});
因此,出于某種原因,這有效并且不會產生我之前遇到的錯誤。我現在可以與前端和后端通信并發送資料和電子郵件。
但我不知道為什么這行得通,而另一個沒有。我也沒有改變我的 package.json
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/406424.html
標籤:
