在过去的三天里,我一直在与错误“跨源请求被阻止:相同的源策略不允许读取http://localhost:8080/demomongo/templateapp/login上的远程资源。”(原因:缺少CORS头'Access-Control-Allow-Origin')。
Here is my code kindly help.
Login.html
<html ng-app="LoginApp">
<body>
<script src="angular.min.js"></script>
<script src="LoginApp.js"> </script>
<div ng-controller="loginController as login">
Username <input type="text" ng-model="username" /><br/>
Password <input type="text" ng-model="password" /><br/>
<button ng-click="validate()">Validate</button>
</div>
<br/> <a href="Reg.html">Register Me/New user</a>
</body>
</html>
LoginApp.js
(function(){
var app;
app=angular.module('LoginApp',[]);
app.controller('loginController',function($scope,$http){
var dataObj = {
"name" : "Java Honk",
"password" : "NY"
};
$scope.validate = function() {
dataObj.name=$scope.username;
dataObj.password=$scope.password;
//if($scope.username=="sam" && $scope.password=="pwd")
// console.log("password match");
// else
//console.log("username/pwd not matching");
$http.post('http://localhost:8080/demomongo/templateapp/login', dataObj)
.success(function(responseData) {
$scope.responseData = responseData;
console.log(responseData);
}).error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
}
});
})();
CORSFilter.java
package com.demo.mongo.example.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;
public class CORSFilter extends OncePerRequestFilter {
private static final Log LOG = LogFactory.getLog(CORSFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOG.trace("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
// response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "1");
}
filterChain.doFilter(request, response);
}
}
//templatecontroller.java
package com.demo.mongo.example.controller;
import java.util.List;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.demo.mongo.example.model.UserDetails;
@RestController
@RequestMapping("/templateapp")
public class TemplateController {
@CrossOrigin
@RequestMapping(value="/login", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String validateUser(@RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
/*UserDetails obj=new UserDetails();
List<UserDetails> values=obj.UserDetails(udata.getName(),udata.getPassword());
if(values.size()>0){
return "welcome udata.getName";
}
else
{
return "please register using registration link";
}*/
if(udata.getName().equalsIgnoreCase("admin") && udata.getPassword().equalsIgnoreCase("admin"))
{
return "welcome admin";
}
else
{
return "password mismatch/not an admin";
}
}
@CrossOrigin
@RequestMapping(value="/addUser", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String addUser(@RequestBody UserDetails udata,UriComponentsBuilder ucBuilder) {
return " new user details: name "+ udata.getName() + " Email Id " + udata.getEmailid() ;
}
}
package com.demo.mongo.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class UserDetails {
@Id
private String name;
private String password;
private String emailid;
private int contact;
public UserDetails(){}
public UserDetails(String name,String password,String emailid,int contact){
this.name=name;
this.password=password;
this.emailid=emailid;
this.contact=contact;
}
public void setName(String name){
this.name=name;
}
public void setPassword(String password){
this.password=password;
}
public void setEmailid(String emailid){
this.emailid=emailid;
}
public void setContact(int contact){
this.contact=contact;
}
public String getPassword(){
return this.password;
}
public String getName(){
return this.name;
}
public int getContact(){
return this.contact;
}
public String getEmailid(){
return this.emailid;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.demo.mongo.example" />
<mvc:annotation-driven />
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="localhost" />
</bean>
<!-- MongoTemplate for connecting and querying the documents in the database -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo" />
<constructor-arg name="databaseName" value="test" />
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
<web-app 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_2_5.xsd"
version="2.5">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
<!-- Add this to your web.xml to enable "CORS" -->
<filter>
<filter-name>cors</filter-name>
<filter-class>com.demo.mongo.example.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.demo.mongo.example</groupId>
<artifactId>demomongo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demomongo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<finalName>demomongo</finalName>
</build>
</project>
共1个答案
匿名用户
在Filter中设置标题“Access-Control-Allow-Origin”。如果头没有出现,请确保它是链接的。调试或记录它。
相关问题
- AngularJS广播在第一个控制器加载时不工作
- 角度无线电 ng-change 仅在第一次工作
- 密钥表究竟是如何工作的?
- 在Windows Git bash中工作时,gitlab的Git克隆在linux上失败
- 如何将Spring与JavaFX一起使用?
- JavaFX2中的Fxml和Spring如何定义依赖注入
- Eclipse/STS中的Gradle项目有可能解决同一个工作空间中其他Gradle项目的依赖关系吗?
- Spring 引导@Mapper Bean 创建问题:应用程序无法启动。错误:考虑定义一个类型的 bean
- 想在我的Spring启动应用程序完成执行后自动杀死我的localhost8080
- 无法处理 Spring 安全性异常
- 与Spring Boot一起发布JavaFX 2
- 在JRE容器之前使用Spring Gradle依赖容器会导致编译错误
- JavaFx自定义控件和Spring DI
- JavaFX fxml -如何将Spring DI与嵌套的自定义控件一起使用?
- Spring启动无法连接到我的postgresql aws rds数据库
- 无法使用 SpringApplication.exit() 终止 Spring 启动作业应用程序,因为 Tomcat 错误“套接字接受失败”
- Springfox到OpenAPI Springdocs迁移:@ apimplicitparam(allow multiple = true)等价?
- 带有 Spring 引导 3.0.0 日志记录问题的本机映像
- React Components的导入语句在ES6中的工作原理[重复]
- 本地查询中的Spring JPA存储库子查询
在Filter中设置标题“Access-Control-Allow-Origin”。如果头没有出现,请确保它是链接的。调试或记录它。
问题内容: 我们添加到我们现有的项目中。 从这一刻起,我们从服务器收到401 错误。 这是因为没有标头附加到响应。为了解决这个问题,我们Filter在退出过滤器之前的链中添加了我们自己的过滤器,但是该过滤器不适用于我们的请求。 我们的错误: XMLHttpRequest无法加载。所请求的资源上不存在“ Access-Control-Allow-Origin”标头。http://localhost:
这是因为响应中没有附加头。为了解决这个问题,我们添加了自己的筛选器,它位于注销筛选器之前的链中,但该筛选器不适用于我们的请求。 我们的错误: XMLHttpRequest无法加载。请求的资源上没有“access-control-allow-origin”标头。因此,不允许访问Origin。响应的HTTP状态代码为401。 我们的过滤器 我们的申请 我们的筛选器是从Spring-Boot注册的: 尝
更新:我尝试将过滤器实现为OncePerRequestFilter,但仍然不起作用。有人能在这里进一步帮助我吗? 更新2:也试过这个,http://software.dzhuvinov.com/cors-filter-installation.html,运气不好 更新#3:这是我在控制台中的输出,我可以看到响应没有添加任何标题: register.html
Cors过滤器的配置概述。 { "name": "cors", "config": {} } 返回 上一级
这是一个基于路由或虚拟主机的处理跨源共享资源请求(Cross-Origin Resource Sharing)的过滤器设置。标题相关的含义,请参阅下面的连接。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS https://www.w3.org/TR/cors/ v1 API 参考 v2 API 参考 返回
所以,基本上,前端使用reactJS,后端Spring Boot(微服务,zuul充当网关),当然,如果没有CORS的东西,他们什么也做不了。 我们使用了这段代码 它起作用了,但不再起作用了。我正在使用Postman检查发送回来的标头,但这些都不在那里。 我该怎么办?我可以在每个微服务中使用一个简单的CORS过滤器,但让Zuul处理这一切会容易得多。因为无论如何所有请求都会通过它。 有什么建议吗?