我正在使用 Typescript Fetch 包裝器來發布和獲取請求并在發布時獲取空物件(獲取作業正常)(在我使用 Vanilla Js 并且一切正常之前)Nodejs:
const express = require('express');
const fs = require('fs');
const app = express();
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.use(express.json());
app.post('/login', (req, res) => {
let isLogged = login(req.body);
console.log(req.body);
res.status(200).json(isLogged);
});
我的打字稿提取包裝器:
async function fetchWrapper<T>(path: string, config: RequestInit): Promise<T> {
const request = new Request(path, config);
const response = await fetch(request);
if (!response.ok) {
throw new Error(
`name: ${response.status}, message: ${response.statusText}`
);
}
// return empty object
return response.json().catch(() => ({}));
}
export async function post<T, U>(
path: string,
body: T,
config?: RequestInit
): Promise<U> {
const init = { method: 'post', body: JSON.stringify(body), ...config };
return await fetchWrapper<U>(path, init);
}
我的帖子請求:
const res = await fetch.post(`${url}/login`, {
body: inputData,
headers: { 'Content-Type': 'application/json' },
});
輸入資料不為空
uj5u.com熱心網友回復:
這里的問題是您使用了錯誤的Content-Type標頭值。express.json決議application/json內容型別,而您發送application/x-www-form-urlencoded。解決方案是更改您發送的內容型別,或者添加另一個中間件bodyparser來決議application/x-www-form-urlencoded正文。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349255.html
