简体   繁体   English

如何在 typescript express 中设置 cors()

[英]how to set up cors() in typescript express

In one of my projects, simply this worked:在我的一个项目中,这很有效:

import cors from "cors";

server.use(cors());

but currently, I am having this lovely typescript warning message in my new project:但目前,我在我的新项目中收到这条可爱的 typescript 警告消息:

  No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
      Type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
        Types of parameters 'req' and 'req' are incompatible.
          Type 'Request<ParamsDictionary, any, any, ParsedQs>' is not assignable to type 'Request<never, never, never, never>'.
            Type 'ParamsDictionary' is not assignable to type 'never'.ts(2769)

then I tried to set up custom cors middleware and use it:然后我尝试设置自定义 cors 中间件并使用它:

import { NextFunction ,Request,Response} from 'express';

export const Cors=(req:Request, res:Response, next:NextFunction) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
      "Access-Control-Allow-Methods",
      "OPTIONS, GET, POST, PUT, PATCH, DELETE"
    );
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    if (req.method === "OPTIONS") {
      return res.sendStatus(200);
    }
    next();
  };

   server.use(Cors());

this time i am having another lovely error:这次我遇到了另一个可爱的错误:

No overload matches this call.没有过载匹配此调用。 The last overload gave the following error.最后一个重载给出了以下错误。 Argument of type 'Response | 'Response | 类型的参数undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'. undefined' 不可分配给 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>' 类型的参数。 Type 'undefined' is not assignable to type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'类型“未定义”不可分配给类型“RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>”

This is because of some ambiguity in the generic typing for the cors library.这是因为 cors 库的通用类型存在一些歧义。 The easiest way I've found to fix this is simply explicitly specify the request type for the cors method.我发现解决此问题的最简单方法就是明确指定cors方法的请求类型。

import { Request } from "express";
import cors from "cors";

server.use(cors<Request>());

From express official documentation :来自快递官方文档

For all cors request do the following对于所有 cors 请求,请执行以下操作

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Or if you want to add a single route config:或者,如果您想添加单个路由配置:

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

For more specific configs you can check the official docs, they are quite simple and straightforward对于更具体的配置,您可以查看官方文档,它们非常简单明了

In my case:就我而言:

{
  "cors": "^2.8.5",
  "express": "^4.18.1",
  "typescript": "^4.8.4",
}

it works:有用:

import cors = require("cors");
app.use(cors<Request>());

i found this solution:我找到了这个解决方案:

Using:使用:

...
  "express": "^4.17.1",
  "@types/express": "^4.17.9",
...

replace ".use(cors())" for将“.use(cors())”替换为

.use((req, resp, next) => {
    next()
  }, cors({ maxAge: 84600 }))

Source: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647来源: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM