javascript - 尝试将我的应用程序发布到 Heroku 上时出现错误 :"No ' Access-Control-Allow-Origin' header 出现在请求的资源上”

标签 javascript java spring-boot vue.js heroku

开发者们好,我只是想将这个简单的应用程序上传到我的 Herokuapp,但是每当我尝试登录或注册与后端建立连接时都会出现此错误: “从源 ' https://xxxxxxxxx.herokuapp.com//mini/all_product/registering ' 获取数据的访问已被 CORS 策略阻止:请求的资源上不存在 'Access-Control-Allow-Origin' header 。如果不透明的响应满足您的需求,将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。” 两者都尝试从前端登录或注册。看到我尝试在前端的 header 对象中添加的错误,对这样的参数进行排序。让我们说一下我的注册操作:

VUEX

const herokuUrl = "https://xxxxxxxxxxxxx.herokuapp.com/";

ACTION
     getUserSignedUp({ commit, dispatch }, payload) {
      // console.log(payload);

      fetch(herokuUrl + "mini/all_product/registering", {
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          "mode":"Access-Control-Allow-Origin",----------------------->PUT THIS HERE
        },
        method: "POST",
        body: JSON.stringify(payload),
      })
        .then((userData) => {
          // console.log("data sent :", JSON.stringify(userData));
          return userData.json();
        })
        .then((userData1) => {
          if (userData1.Error) {
            alert("fail on register", userData1);
            commit("setUserAuth", false);
          } else {
            alert("Success", userData1);
            dispatch("getUserLogIn", payload);
            commit("setUserAuth", true);
           }
        })
        .catch((error) => {
         alert("error", error);
        });
    },

但没有成功。

我还附加了我的后端应用程序 cors 配置

package com.miniAmazon;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.hibernate.mapping.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;


@Configuration
@EnableWebSecurity
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
    @Autowired
    UserRepository userRepository;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(inputName-> {
            User user =userRepository.findByuserName(inputName);
            if (user != null) {
                return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getUserPassword(),
                        AuthorityUtils.createAuthorityList("USER"));
            }
            else {
                throw new UsernameNotFoundException("Unknown user: " + inputName);
            }
        });
    }
}
@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.authorizeRequests()
                .antMatchers("/mini/all_products/user").permitAll()
                .antMatchers("/mini/all_products/provider").permitAll()
                .antMatchers("mini/all_products/user_dashboard/purchase/{id}").permitAll()
                .antMatchers("/mini/all_products/allpurchase_view").permitAll()
                .antMatchers("/mini/all_products/provider/product_added").permitAll()
                .antMatchers("/mini/all_products/delete/{id}").permitAll()
                .antMatchers("/mini/all_products/provider/product_edited/{id}").permitAll()
                .antMatchers("/mini/all_products/user/product_rated/{id}").permitAll()
                .antMatchers("/mini/all_products/one_selected/purchase_view/{id}").permitAll()
                .antMatchers("/mini/all_products/user_dashboard/detail_each_purchase/final_view/{idPurchase}").permitAll()
                .antMatchers("/mini/all_products/user_dashboard/final_view").permitAll()
                .antMatchers("/mini/all_products/one_selected/purchase_view/{id}").permitAll()
                .antMatchers("/mini/all_product/registering").permitAll()
//              .antMatchers("/mini/all_product/registering/provider").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/rest/**").hasAuthority("ADMIN")
                .antMatchers("/**").hasAuthority("USER")
//              .antMatchers("/**").hasAuthority("PROVIDER")
                .anyRequest().fullyAuthenticated();
        /////Autorizaciones y permisos para los distintos niveles de seguridad que tendria el usuario segun su casificacion
        http.formLogin()
                .usernameParameter("name")
                .passwordParameter("password")
                .loginPage("/api/login");

        http.logout().logoutUrl("/api/logout");

        http.csrf().disable();

        http.exceptionHandling().authenticationEntryPoint((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

        http.formLogin().successHandler((req, res, auth) -> clearAuthenticationAttributes(req));

        http.formLogin().failureHandler((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

        http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
//        http.headers().frameOptions().disable();
        http.headers().frameOptions().sameOrigin();
    }

    private void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        }
    }
    @Bean////importando Heroku a la base de datos
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // will fail with 403 Invalid CORS request
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

关于为什么会发生这种情况有什么建议吗?提前致谢!祝你有美好的一天!!!

最佳答案

问题来自后端,您需要在后端服务器上启用cors 请按照 Spring 官方网站上的以下步骤操作: https://spring.io/guides/gs/rest-service-cors/#_enabling_cors

谢谢您,我希望这个答案有用

关于javascript - 尝试将我的应用程序发布到 Heroku 上时出现错误 :"No ' Access-Control-Allow-Origin' header 出现在请求的资源上”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61319072/

相关文章:

javascript - 在事件的 Accordion 面板下选择一个类

java - 为什么 Java Thread 会扭曲控制台的打印

java - 正则表达式替代PreparedStatement IN子句?

spring-boot - Spring Reactive kafka Receiver 总是将引导服务器覆盖到本地主机

java - SpringBoot,如何在不使用ldif的情况下使用LDAP进行身份验证?

javascript - 如何创建带有淡出背景的阅读更多链接?

javascript - 图像不生成 D3

javascript - 删除换行符而不\r\n

java - 减少相同异常的记录

spring-boot - Kafka Schema Registry 出现错误 Unexpected character ('<' (code 60)) : expected a valid value (number, String, array, object, 'true' , 'false' )