我是否使用cURL正确模拟了CORS,是否需要执行OPTIONS请求

时间:2019-01-12 02:35:56

标签: c rest cors

我不太擅长Web服务器开发,也不了解http标头到底如何工作。我已经读了很多书,但还是有些困惑。目前,我正在尝试使用cURL模拟CORS请求。 (需要用于个人发展)。为此,我找到了simple REST server written in C(C是我最熟悉的语言)。代码实际上是located here。我发现this post解释了如何模拟CORS。

问题出在这里

如果我跑步

curl -H "Origin: http://localhost:3000" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X OPTIONS --verbose \
  http://localhost:8537/test

请求失败,并显示以下响应

*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 8537 failed: Connection refused
*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 8537 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8537 (#0)
> OPTIONS /test HTTP/1.1
> Host: localhost:8537
> User-Agent: curl/7.61.1
> Accept: */*
> Origin: http://localhost:3000
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: X-Request-With
>
< HTTP/1.1 404 Not Found
< Connection: Keep-Alive
< Content-Length: 32
< Access-Control-Allow-Origin: *
< Date: Sat, 12 Jan 2019 02:21:59 GMT
<
* Connection #0 to host localhost left intact
Page not found, do what you want

但是,如果我使用-X POST而不是-X OPTIONS来运行相同的请求,即

curl -H "Origin: http://localhost:3000" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: X-Requested-With" \
  -X POST --verbose \
  http://localhost:8537/test

请求成功,并返回以下响应:

*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 8537 failed: Connection refused
*   Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 8537 failed: Connection refused
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8537 (#0)
> POST /test HTTP/1.1
> Host: localhost:8537
> User-Agent: curl/7.61.1
> Accept: */*
> Origin: http://localhost:3000
> Access-Control-Request-Method: POST
> Access-Control-Request-Headers: X-Request-With
>
< HTTP/1.1 200 OK
< Connection: Keep-Alive
< Content-Length: 19
< Access-Control-Allow-Origin: *
< Date: Sat, 12 Jan 2019 02:25:28 GMT
<
Hello World!
* Connection #0 to host localhost left intact
(null)

如果执行,我得到的结果相同

curl -H "Origin: http://localhost:3000" -X OPTIONS --verbose http://localhost:8537/test

curl -H "Origin: http://localhost:3000" -X POST --verbose http://localhost:8537/test

即,该请求因OPTIONS请求而失败,而由于POST请求而成功。

代码确实允许CORS(至少我认为是这样)。 Here is the line of code that does it

u_map_put(instance.default_headers, "Access-Control-Allow-Origin", "*");

所以这是问题:

  1. 要模拟CORS,我需要使用OPTIONS请求还是POST请求?
  2. 如果要编写与示例中的服务器类似的服务器,我是否需要实现OPTIONS响应,还是可以摆脱POST / GET?

1 个答案:

答案 0 :(得分:1)

在CORS中,obj用于preflight requests。 如果仅发出“简单” CORS请求,则不一定需要处理OPTIONS请求。

您可以阅读简单CORS请求here的定义。