我有以下代码可以在生产中使用:
redirect_to"/mycontroller/index.html#&panel1-2?error=无效的会员ID和/或出生日期"
在开发过程中(使用Webrick),我收到以下错误消息:
错误URI::InvalidURI错误:错误的URI(不是URI吗?):http://localhost:3000/mycontroller/index.html#&panel1-2?error=会员ID和/或出生日期无效
但是,如果我在浏览器地址栏中复制并粘贴所谓的坏URI,它就会起作用!
我尝试过错误消息文本的各种组合,单词之间的空格是导致错误消息文本出现的原因。我可以通过使用URI.escape或其他一些技术来转义空格来使其工作,但之后我必须在代码中更改数百个这样的出现,这很好。
谢谢你花时间帮忙。
如下所示,您的URI实际上是无效的。您的URI中不能有未跳过的空格。
1.9.3p194 :001 > require 'URI' => true
1.9.3p194 :002 > URI.parse('http://localhost:3000/mycontroller/index.html#&panel1-2?error=Invalid Member ID and/or Date of Birth')
URI::InvalidURIError: bad URI(is not URI?): http://localhost:3000/mycontroller/index.html#&panel1-2?error=Invalid Member ID and/or Date of Birth
from /Users/ccashwell/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/common.rb:176:in `split'
from /Users/ccashwell/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/common.rb:211:in `parse'
from /Users/ccashwell/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/common.rb:747:in `parse'
from (irb):2
from /Users/ccashwell/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
您应该escape
URI:
1.9.3p194 :003 > URI.escape('http://localhost:3000/mycontroller/index.html#&panel1-2?error=Invalid Member ID and/or Date of Birth')
=> "http://localhost:3000/mycontroller/index.html%23&panel1-2?error=Invalid%20Member%20ID%20and/or%20Date%20of%20Birth"
然后您可以redirect_to
转义的URI:
redirect_to URI.escape('http://localhost:3000/mycontroller/index.html#&panel1-2?error=Invalid Member ID and/or Date of Birth')
URL的空格通常替换为%20
。大多数网络浏览器都会自动为您替换它,因此这就解释了为什么浏览器可以访问该网站。只要用%20
代替你的空格,你就应该做好了。