CORS 필터가 올바르게 작동하지 않음
웹스톰 어플리케이션에서 백엔드 어플리케이션으로 요청을 전송하려고 하는데 둘 다 다른 포트에 있으며 angular를 사용하여 작업하고 있습니다.프런트 엔드의 JS와 백엔드의 Java.저는 CORS 필터에 대해 조금 읽었고, 크로스 오리진 요청을 수행하려면 이러한 필터들을 구현해야 한다는 것을 배웠습니다.하지만, 이렇게 한 후, 제 실수입니다.
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access. http://localhost:8080/register?password=&username=
XMLHttpRequest cannot load http://localhost:8080/register?password=&username=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access.
제가 잘못했다고 믿게 된 것은 전혀 변하지 않았습니다.요구를 송신한 코드는 다음과 같습니다.
var charmanderServices = angular.module('charmanderServices', ['ngResource']);
var hostAdress = "http://localhost:8080";
charmanderServices.factory("register", ["$resource",
function($resource){
console.log('in service');
return $resource(hostAdress + "/register", {}, {
'registerUser' : { method: 'POST', isArray: false,
params: {
username: '@username',
password: '@password'
}
},
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
});
}
]);
corsFilter는 다음과 같이 기술되어 있습니다.
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//This is not even printing
System.out.println("Cheers lads, I'm in the filter");
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, X-Auth-Token, Content-Type");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
이것은 my web.xml 입니다.
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd">
<display-name>Project</display-name>
<!-- Load Spring Contexts -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CORS Filter -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.robin.filters.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
요구를 수신하는 컨트롤러는 다음과 같습니다.
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/register" , method= RequestMethod.POST, produces = "application/json")
@ResponseBody
public boolean register(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password){
System.out.println("Im in register hurray");
return userService.register(username, password);
}
}
업데이트: 필터를 OncePerRequestFilter로 구현하려고 했지만 아직 작동하지 않습니다.여기서 더 도와줄 사람 있나요?
업데이트 #2:이것도 해봤어. http://software.dzhuvinov.com/cors-filter-installation.html, No ruck.
업데이트 #3:콘솔에서의 출력은 다음과 같습니다.응답에 헤더가 추가되어 있지 않은 것을 알 수 있습니다.
Request URL:http://localhost:8080/register?password=g&username=g
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:63343
Referer:http://localhost:63343/Project/index.html?uName=g&uPassword=g&uPasswordConfirm=g
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36
Query String Parametersview sourceview URL encoded
password:g
username:g
Response Headersview source
Allow:GET, HEAD, POST, PUT, DELETE, OPTIONS
Content-Length:0
Date:Fri, 04 Apr 2014 09:50:35 GMT
Server:Apache-Coyote/1.1
업데이트 #4:필터에 @Component가 아닌 @WebFilter로 주석을 달았지만 도움이 되지 않았습니다.
업데이트 #5:다음은 applicationContext.xml 파일입니다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.robin"/>
<mvc:annotation-driven/>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<array>
<value>com.robin.model</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>com.robin.model.User</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--Driver for mysqldb -->
<import resource="mysql-context.xml"/>
</beans>
컨트롤러와 register.html 파일의 코드도 여기에 추가했습니다.
charmanderControllers.controller('registerController', ['$scope', 'register',
function($scope, register){
$scope.username = '';
$scope.password = '';
$scope.register = function () {
register.registerUser({'username': $scope.username, 'password': $scope.password}).$promise.then(function(data){
switch(data.response){
case true:
//succes
$scope.registered = true;
$scope.userExists = false;
break;
case false:
//user exists
$scope.registered = false;
$scope.userExists = true;
break;
}
console.log(data.response);
})
};
$scope.checkValidRegister = function (invalid) {
console.log(invalid);
console.log($scope.passwordConfirm);
console.log($scope.password);
console.log($scope.username);
if (invalid || $scope.password != $scope.passwordConfirm) {
console.log("I shouldnt be here");
$scope.validation = true;
if ($scope.password != $scope.passwordConfirm) {
$scope.passwordError = true;
}
} else {
register();
}
};
}]);
등록. 삭제.
<h1>Register now!</h1>
<form method="post" class="register" novalidate>
<p>
<label for="email">E-mail:</label>
<input type="text" name="login" id="email" placeholder="E-mail address..." required ng-model="username">
</p>
<p>
<label for="password">Password:</label>
<input type="password" name="password" id="password" placeholder="Password..."
required ng-model="password">
</p>
<p>
<label for="confirm_password">Confirm password: </label>
<input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm password..."
required ng-model="passwordConfirm">
<span ng-show="passwordError">Passwords do not match!</span>
</p>
<p class="register_submit">
<button type="submit" class="register-button" ng-click="checkValidRegister()">Register</button>
</p>
</form>
코드와 설정은 일반적으로 양호해 보여 로컬 환경에서 실행할 수 있었습니다.에서 @Component 주석을 삭제하십시오.SimpleCORSFilter플레인 서블릿필터로 사용하기 때문에 스프링 컨텍스트의 일부가 될 필요는 없습니다.
UPD. Tomcat 7에는 자체 CORS 필터 구현이 있습니다.상세한 것에 대하여는, 메뉴얼과 소스코드를 참조해 주세요.기본 구성을 반영하도록 헤더를 수정했습니다. 이제 예상대로 작동합니다.
이미 스프링을 사용하고 있고 스프링 4.2 이상을 사용하고 있다면 필요 없습니다.CorsFilter는 컨트롤러 메서드에 주석을 달기만 하면 됩니다.여기 이것에 관한 훌륭한 기사가 있습니다. 읽을 가치가 있습니다.
다른 플랫폼의 CORS 설정을 설명하는 훌륭한 리소스도 확인해 주십시오.
플레인 필터 실장을 사용한 작업 예를 다음에 나타냅니다.
컨트롤러:
@Controller
public class UserController {
private static Logger log = Logger.getAnonymousLogger();
@RequestMapping(
value = "/register",
method = RequestMethod.POST,
consumes = "application/x-www-form-urlencoded")
@ResponseBody
public String register(@RequestParam(value = "user") String username,
@RequestParam(value = "password") String password) {
log.info(username + " " + password);
return "true";
}
}
필터:
public class CorsFilter implements Filter {
private static final Logger log = Logger.getAnonymousLogger();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info("Adding Access Control Response Headers");
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
web.xml 필터 매핑:
<filter>
<filter-name>cors</filter-name>
<filter-class>com.udalmik.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/register</url-pattern>
</filter-mapping>
JS가 별도의 웹 앱(JQuery)에서 요청을 수행합니다.
$(document).ready(function() {
$('#buttonId').click(function() {
$.ajax({
type: "POST",
url: "http://localhost:8080/register",
success : function(data){
console.log(data);
},
data : {
user : 'test.user@acme.com',
password : 'password'
}
});
}
}
언급URL : https://stackoverflow.com/questions/22846309/cors-filter-not-working-as-intended
'programing' 카테고리의 다른 글
| 각진 이유JS 통화 필터는 괄호로 음수를 포맷합니까? (0) | 2023.03.20 |
|---|---|
| AngularJS: "안전한 컨텍스트에서 안전하지 않은 값 사용 시도" 해결 방법 (0) | 2023.03.20 |
| reactj의 인라인 스타일에 벤더 프리픽스를 적용하려면 어떻게 해야 하나요? (0) | 2023.03.20 |
| ReactJS: onClick 핸들러를 자 컴포넌트에 배치해도 부팅되지 않음 (0) | 2023.03.20 |
| Wordpress - 작성자 이미지 가져오기 (0) | 2023.03.20 |