我已经有效地使用了wiremock一段时间了,我想启用对模拟API的CORS访问。
我尝试在响应标头中设置Access-Control-Allow-Origin:*和其他标头,两者都无济于事。
以下是我的映射示例:
{
"request": {
"method": "POST",
"urlPattern": "/api/v2/general/login[\\/\\&\\?]*",
"bodyPatterns": [{
"equalToJson": "{\"password\":\"password\",\"username\":\"john@cougar.com\"} ",
"jsonCompareMode": "LENIENT",
"ignoreArrayOrder" : true,
"ignoreExtraElements" : true
}]
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "*",
"Access-Control-Allow-Headers": "Accept, Content-Type, Content-Encoding, Server, Transfer-Encoding",
"X-Content-Type-Options" : "nosniff",
"x-frame-options" : "DENY",
"x-xss-protection" : "1; mode=block"
},
"bodyFileName": "/login_response_johncougar.json"
}
}
我在这做错了什么导致CORS不起作用?
提前致谢。
答案 0 :(得分:2)
以下是一个示例,其中有效
{
"request":
{
"urlPattern": "/country/([a-z]*)",
"method": "GET"
},
"response":
{
"status": 200,
"headers":
{
"Content-Type" : "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "*",
"Access-Control-Allow-Headers": "Accept, Content-Type, Content-Encoding, Server, Transfer-Encoding",
"X-Content-Type-Options" : "nosniff",
"x-frame-options" : "DENY",
"x-xss-protection" : "1; mode=block"
},
"body": "{ \"statusCode\" : \"S1000\", \"statusDescription\" : \"Success\", \"content\" : [ { \"id\" : \"1111\", \"name\" : \"aaaa\"}, { \"id\" : \"2222\", \"name\" : \"asd\" } ] }"
}
}
原样使用它,线条在间距方面很奇特,这里我使用了一个空格而不是标签,希望它有所帮助。
答案 1 :(得分:0)
我有同样的问题。经过长时间的搜索并没有找到解决方案,我开始使用groovy文件,最后找到了解决方案。
您只需要在header()方法中添加每个标头。这将解决问题。因此,您的示例常规合同将如下所示:
{
"request": {
"method": "POST",
"urlPattern": "/api/v2/general/login[\\/\\&\\?]*",
"bodyPatterns": [{
"equalToJson": "{\"password\":\"password\",\"username\":\"john@cougar.com\"} ",
"jsonCompareMode": "LENIENT",
"ignoreArrayOrder": true,
"ignoreExtraElements": true
}]
},
"response": {
"status": 200,
"headers": {
header("Content-Type": "application/json"),
header("Access-Control-Allow-Origin": "*"),
header("Access-Control-Allow-Methods": "*"),
header("Access-Control-Allow-Headers": "Accept, Content-Type, Content-Encoding, Server, Transfer-Encoding"),
header("X-Content-Type-Options": "nosniff"),
header("x-frame-options": "DENY"),
header("x-xss-protection": "1; mode=block")
},
"bodyFileName": "/login_response_johncougar.json"
}
}
我希望它可以解决您的问题(实际上,如果您使用常规合同,这将很有用)。
答案 2 :(得分:0)
我刚刚设法解决了此问题。实际上,解决方案已经在这里Adding headers to Jetty in Wiremock。
由于您的浏览器在发出任何实际请求之前发送了CORS预检请求,因此您需要设置您的Wiremock来存根OPTIONS请求并发送回标头。
例如,
Access-Control-Allow-Origin = "*",
Access-Control-Allow-Headers: "content-type",
Access-Control-Allow-Methods = "POST, GET"
。
Access-Control-Allow-Headers的值必须与Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response中包含的Access-Control-Request-Headers头相同。
您所有的回复也必须发送回标头"Access-Control-Allow-Origin": "*"
。