NodeJS CORS不过滤任何内容 [英] NodeJS cors don't filter anything

查看:57
本文介绍了NodeJS CORS不过滤任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试遵循在此处此处.但无论如何,似乎都接受了路线:

I tried to follow the tutorials I found here and here. But it appears the routes are accepted no matter what:

const config = require('config')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()

var corsOptions = {
  origin: 'https://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}

app.get('/test', function (req, res) {
  console.log(req.get('host')+' - '+req.get('origin'))
  res.send('OK')
})

app.get('/test2', cors(corsOptions), function (req, res) {
  console.log(req.get('host')+' - '+req.get('origin'))
  res.send('OK2')
})

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(config.get('app.port'))

当我在浏览器中输入URL或在控制台中获取URL时,控制台中将显示同一行: myAPIwebsite.com-未定义(myAPIwebsite.com是节点API所在的位置)可以访问.)

When I enter the URLs in the browser or when I fetch it in the console, I have the same line in the console: myAPIwebsite.com - undefined (myAPIwebsite.com is where the node API is accessible).

我想要的是/test 可以在除/test2 之外的任何地方使用,仅适用于来自example.com的请求.

What I would like is that the /test works from anywhere but /test2 only for requests coming from example.com.

有人可以帮我吗?在此先感谢:)

Could anybody give me a hand? Thanks in advance :)

推荐答案

默认情况下,来自一个域但去往另一个域的许多/多数请求被阻止.CORS标头可让您有选择地解除这些限制.

By default many/mosts requests that originate from one domain, but go to another domain are blocked. CORS headers allow you to selectively lift those restrictions.

在浏览器地址栏中直接打开URL从未被阻止,因此CORS无法帮助您取消阻止"最初未被阻止的内容.

Directly opening a url in your browser addressbar was never blocked, so CORS can't help you 'unblock' what was not blocked in the first place.

CORS中的S代表共享.标头仅用于放宽限制.

The S in CORS stands for sharing. The headers are only for loosening restrictions.

这篇关于NodeJS CORS不过滤任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆