简体   繁体   English

在 Express 应用程序中添加参数时出现 CORS 错误

[英]CORS Error when adding a parameter in an Express app

I can't at all figure out why this is not working.我完全不明白为什么这不起作用。

I have an express app hosted on Heroku that basically does this我在 Heroku 上托管了一个 Express 应用程序,它基本上可以做到这一点

var urlMetadata = require('url-metadata')

var express = require('express')

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

app.use(cors())

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

app.get('/prod/:url', function (req, res, next) {

    var url = decodeURI(req.params.url);

    urlMetadata(url).then(
        function (metadata) {
            res.json({
                metadata
            });
        },
        function (error) {
            console.log(error)
        })
})

Client side客户端

    axios
      .get(`https://git.heroku.com/egosmos-meta.git/prod`, {
        params: {
          url,
        },
      })
      .then((response) => {
        console.log(response);
      });

    axios
      .get(`https://egosmos-meta.herokuapp.com/products`)
      .then((response) => {
        console.log(response);
      });

And this is what I'm getting这就是我得到的

在此处输入图片说明

So /products works, but /prod/:url throws a CORS error所以/products有效,但/prod/:url引发 CORS 错误

Thanks for your help!谢谢你的帮助!

params in Axios defines the query parameters, eg ?url=http://example.com but your Express app is expecting a route parameter . Axios 中的params定义了查询参数,例如?url=http://example.com但您的 Express 应用程序需要一个路由参数

Change your client-side code to the following将您的客户端代码更改为以下内容

axios.get(`https://git.heroku.com/egosmos-meta.git/prod/${encodeURIComponent(url)}`)

You get a CORS error because you have no route for /prod?url=... so the CORS middleware isn't kicking in.您收到 CORS 错误,因为您没有/prod?url=...路由,因此 CORS 中间件没有启动。

try using the corsOption..尝试使用 corsOption ..

var cors = require('cors') var cors = require('cors')

var corsOptions = { origin: 'https://git.heroku.com', optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204 } var corsOptions = { origin: 'https://git.heroku.com', optionsSuccessStatus: 200 // 一些旧版浏览器(IE11、各种 SmartTV)在 204 上卡住了}

app.use(cors(corsOptions)) app.use(cors(corsOptions))

Also if for the axios try axios.get( https://git.heroku.com/egosmos-meta.git/prod/${url} ).then()另外,如果对于 axios 尝试 axios.get( https://git.heroku.com/egosmos-meta.git/prod/${url} ).then()

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

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