[英]Can't access body data from fetch PUT to express server
我是Web開發的新手,正在嘗試將一些JSON數據發送到運行express的node.js服務器,但出現此錯誤:
無法加載http:// localhost:8888 / :在飛行前響應中,Access-Control-Allow-Methods不允許方法PUT。
我不知道這是什么意思。 這是客戶端獲取:
fetch('http://localhost:8888/', {
method: 'PUT',
body: JSON.stringify(this.exercises),
headers: {
'Content-Type': 'application/json'
}
}).then(res => res.json())
.catch(err => console.error('Error: ' + err))
.then(res => console.log('Success: ' + res));
這是服務器端代碼:
app.put('/', (req, res, next) => {
console.log('PUT request received');
console.log(req.body);
});
服務器似乎甚至沒有收到請求。 我該如何工作? 提前致謝。
確保使用bodyParser(要訪問需要使用body-parser的數據,它允許express讀取body)。 npm install --save body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
設置核心
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
在定義路由之前,請確保已定義配置。 有關cors的信息: https : //developer.mozilla.org/en-US/docs/Web/HTTP/CORS
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.