gpt4 book ai didi

c - 我是否正确地使用 cURL 模拟 CORS?我是否需要实现 OPTIONS 请求

转载 作者:行者123 更新时间:2023-11-30 19:03:19 26 4
gpt4 key购买 nike

我不太擅长 Web 服务器开发,也不了解 http header 到底是如何工作的。我已经读了很多书,但仍然有点困惑。目前我正在尝试使用 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 吗?

最佳答案

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

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

关于c - 我是否正确地使用 cURL 模拟 CORS?我是否需要实现 OPTIONS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54156320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com