java - 问题 Cors:请求的资源上不存在“Access-Control-Allow-Origin”标头
问题描述
我无法解决此错误;我添加了 @CrossOrigin(origins="http://localhost:4200") 但错误仍然存在。
RestAPIController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
(origins = "http://localhost:4200")
@RestController
@RequestMapping("/api/customer")
public class RestAPIController {
@Autowired
CustomerServices customerServices;
@PostMapping("/create")
public ResponseEntity<Message> addNewCustomer(@RequestBody Customer customer) {
try {
Customer returnedCustomer = customerServices.saveCustomer(customer);
return new ResponseEntity<Message>(new Message("Upload Successfully!",
Arrays.asList(returnedCustomer), ""), HttpStatus.OK);
}catch(Exception e) {
return new ResponseEntity<Message>(new Message("Fail to post a new Customer!",
null, e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
.
.
.
.
}
你建议我怎么做?谢谢
我已经尝试了各种方式,我在这个站点上找到并尝试了几个示例,但问题仍然存在。
解决方案
这是一个老问题。
您应该在扩展的 Config 类中添加此覆盖方法WebMvcConfigurer
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("http://localhost:3000")
.maxAge(3600);
}
推荐阅读
- javascript - 跟踪表单提交
- postgresql - postgresql 和 pgadmin docker 容器的问题
- java - 如何在由另一个类构建的类中搜索单词?
- c# - Windows 10 中的 SHChangeNotify 未更新快速访问项目
- javascript - 如何使用 JavaScript 浏览 DropDownList 中的随机项目?
- r - 空白不想被清理
- javascript - 如何从角度组件使用我的节点端点插入数据?
- google-apps-script - onSubmit 触发器在没有提交表单的情况下执行
- r - 我在一列中有几个变量,并想在 R 中创建一个循环,以便我可以将每个变量导出到同一个 Excel 工作簿中它自己的工作表中
- javascript - 我正在尝试将所有相同的值放在我的输入字段中