首页 > 解决方案 > 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
    }
}

标签: node.jstypescriptexpressrequestfetch

解决方案


fetch仅在浏览器中可用。尝试使用node-fetchaxiosnode-request


推荐阅读