我已經在這個問題上作業了 2 天,查看了各個頁面,但找不到一個可行的解決方案。
如果您知道如何使用 async await 函式撰寫它們,請僅回復,如果您知道 fetch api 的答案,請回復。我暫時不是在尋找axios的解決方案。 我有一個后端服務器,它在 localhost 的 8000 埠上運行,前端在 3000 埠上運行。前端是用 React 撰寫的,后端是用 Node/Express 撰寫的。
我能夠成功地從后端服務器發出 GET 請求,但 POST 請求由于某種原因失敗并出現錯誤“VM942:1 POST http://localhost:8000/frontend-to-backend 500 (Internal Server Error)”
后端服務器出現此錯誤:SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse ()
// React-To-Node-Connection
// React "App.js" file
// "package.json" file contains this
// "proxy": "http://localhost:8000"
useEffect(() => {
const getBackend = async () => {
const res = await fetch('backend-to-frontend');
const data = await res.json();
if (!res.ok) {
throw new Error(`Cannot get data from backend server. HTTP Status: ${res.status}`);
}
console.log(data.message);
// Prints "Hi from backend!"
}
getBackend();
const postBackend = async () => {
try {
const res = await fetch('http://localhost:8000/frontend-to-backend',
{
method: 'POST',
mode: 'no-cors',
body: JSON.stringify({ message: 'Hi from frontend!' }),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}
);
if (res.ok) {
const data = await res.json();
console.log(data);
}
} catch (error) {
console.error(error);
}
}
postBackend();
}, []);
現在后端代碼:
app.get('/backend-to-frontend', (req, res) => {
res.json({ message: 'Hi from backend!' });
});
app.post('/frontend-to-backend', (req, res) => {
try {
const reactMessage = JSON.parse(req.body.data);
console.log(`message: ${reactMessage}`);
} catch (err) {
console.error(err);
}
});
如何解決這個問題?請幫忙!
完整的后端服務器代碼可以在這里找到:
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true }));
app.get('/backend-to-frontend', (req, res) => {
res.json({ message: 'Hi from backend!' });
});
app.post('/frontend-to-backend', (req, res) => {
try {
const reactMessage = JSON.parse(req.body.data);
console.log(`message: ${reactMessage}`);
} catch (err) {
console.error(err);
}
});
const port = process.env.PORT || 8000;
app.listen(port, function () {
console.log(`Backend server started on port ${port}.`);
});
uj5u.com熱心網友回復:
req.body.data可能是一個物件(使用除錯器檢查)。如果是這樣,您可能會嘗試在決議之前進行字串化:
JSON.parse(JSON.stringify(req.body.data))
uj5u.com熱心網友回復:
,no-cors您只能使用簡單的標頭,因此您不能 POST JSON(請參閱:提供請求選項)
試試 urlencoded:
const postBackend = async() => {
try {
const res = await fetch('http://localhost:8000/frontend-to-backend', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'message': 'Hi from frontend!'
})
});
if (res.ok) {
const data = await res.json();
console.log(data);
}
} catch (error) {
console.error(error);
}
}
postBackend();
在服務器上,不要 parse req.body,因為它已經由中間件完成:
app.post('/frontend-to-backend', (req, res) => {
console.log('req.body: ', req.body);
try {
const reactMessage = req.body.message;
uj5u.com熱心網友回復:
我終于找到了答案,這是我的示例代碼。我沒有對 React 代碼進行太多更改,所以它幾乎相同,我洗掉了 no cors 部分并將 cors 添加到 Express JS 代碼中。
這是我的反應代碼。
// React-To-Node-Connection
// "package.json" file has the following line
// "proxy": "http://localhost:8000"
// React Code
useEffect(() => {
const getBackend = async () => {
const res = await fetch('/backend-to-frontend');
const data = await res.json();
if (!res.ok) {
throw new Error(`Cannot get data from backend server. HTTP Status: ${res.status}`);
}
console.log(data.message);
}
getBackend();
const postBackend = async () => {
try {
await fetch('http://localhost:8000/frontend-to-backend',
{
method: 'POST',
body: JSON.stringify({ message: 'Hi from frontend!' }),
headers: {
'Content-Type': 'application/json'
}
}
);
} catch (err) {
console.error(err);
}
}
postBackend();
}, []);
這是我的 Express JS 代碼。
const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: true }));
// Express JS Code
const cors = require('cors');
app.use(express.json());
app.use(cors());
app.get('/backend-to-frontend', (req, res) => {
res.json({ message: 'Hi from backend!' });
});
app.post('/frontend-to-backend', (req, res) => {
try {
console.log(req.body.message);
} catch (err) {
console.error(err);
}
});
const port = process.env.PORT || 8000;
app.listen(port, function () {
console.log(`Backend server started on port ${port}.`);
});
謝謝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/426783.html
