我无法从浏览器向本地主机上运行的 Spring 应用程序发送 POST 请求。
我可以发送 GET 请求,并且我的 POST 和 PUT 请求会像 GET 请求一样得到答复。
<html>
<body>
<button onclick="sendPostRequest()">Send POST Request</button>
<script>
function sendPostRequest() {
fetch('http://localhost:8080/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
}).then(response => console.log(response));
}
</script>
</body>
</html>
如果您在 Firefox 中打开调试器 (F12) 并转到“网络”选项卡,则按下按钮时可以看到请求。
在传输的列中您会看到:“CORS Missing Allow Origin”。
修复很简单;在 Java 中创建一个新类:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // Allow requests from any origin
.allowedMethods("GET", "POST", "PUT", "DELETE") // Allow only specific methods
.allowedHeaders("*"); // Allow all headers
}
}