node.js - Express.js 应用程序中的 Typescript Http.Post 或 Fetch
问题描述
我是 Typescript 的新手,我正在尝试制作 OAuth2 服务,就像我在 Express.js 普通应用程序中所做的那样。但我无法使用 Typescript 发出简单的 POST 请求。
我发现的所有示例都说我必须使用“fetch”,但是当我这样做时,我收到一个错误消息fetch is not defined
。
我的代码:
app.get('/oauth/redirect', (req, res, next) => {
let authCode:any = req.query.code;
let view:string;
if (authCode) {
fetch(`${host_url}?client_id=${client_id}&client_secret=${client_secret}&code=${authCode}`, {method: 'POST'})
.then((response) => {
console.log('then!');
console.log(response);
accessToken = response.statusText;
})
.catch((error) => {
console.log('catch!');
console.error(error);
});
view = 'explore';
} else {
view = 'error';
}
res.sendFile(`${__dirname}/views/${view}.html`);
});
我正在使用:
NodeJS: 12.18.3
Express: 4.17.1
TypeScript: 3.9.7
@types/express: 4.17.7
更新
我的package.json
文件:
{
"name": "test",
"version": "1.0.0",
"description": "Typscript test",
"main": "app.js",
"scripts": {
"tsc": "tsc",
"dev": "ts-node-dev --respawn ./app/app.ts",
"prod": "tsc && node ./build/app.js"
},
"author": "Andres Marotta",
"license": "ISC",
"dependencies": {
"@types/express": "^4.17.7",
"express": "^4.17.1",
"ts-node-dev": "^1.0.0-pre.54",
"typescript": "^3.9.7"
},
"devDependencies": {
"@types/node": "^14.0.26",
"@types/node-fetch": "^2.5.7"
}
}
更新 2
这是我的tsconfig.json
文件。这是 Typescript 创建的默认值,我删除了评论并添加了"resolveJsonModule": true
:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"outDir": "./build",
"strict": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
解决方案
fetch仅在浏览器中可用。尝试使用node-fetch、axios或node-request。
推荐阅读
- node.js - Discord Bot 上的状态消息
- pandas - 用Python中的列名确定每一行的最大值
- javascript - 导出的标识符“_default”未在 Babel 的范围跟踪器中声明
- json - 使用 Powershell 将 JSON 转换为 NDJSON
- java - 如何将 HashMap 添加到 Employee 类列表
- azure-active-directory - 在 Azure AD 中的企业应用程序上预配期间获取用户组
- python - 有没有办法直接从 Excel 运行 python 代码?
- java - 如何将算法的输出打印到另一个程序的输入框中?
- laravel - 如何将“客户地址”传递给我的新 Mailer 实例?
- javascript - 导出默认新对象