当前位置: 首页 > 知识库问答 >
问题:

CORS策略阻止对Java Servlet的Angular请求[重复]

尉迟禄
2023-03-14
<form (submit)="onSubmit()">
  <div class="form-group">
    <input
      class="form-control"
      type="text"
      name="usn"
      id="usn"
      [(ngModel)]="usn"
      placeholder="Enter USN HERE"
    />
  </div>
  <input type="submit" value="submit" />
</form>
import { Component } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  private usn: string;
  private url: string = "http://localhost:9090/AngularFetchData/GetData";
  private headers: HttpHeaders;
  constructor(private httpClient: HttpClient) {
    this.headers = new HttpHeaders({
      "Access-Control-Allow-Origin": "http://localhost:4200/",
      "Access-Control-Allow-Methods": "GET, POST, PATCH, PUT, DELETE, OPTIONS",
      "Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token"
    });
  }
  onSubmit() {
    this.httpClient
      .post(
        this.url,
        {
          usn: this.usn
        },
        { headers: this.headers }
      )
      .subscribe((data: any) => {
        console.log(data);
      });
  }
}
package com.angular.fetchdata;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.jdbc.driver.OracleDriver;

import org.json.*;


/**
 * Servlet implementation class GetData
 */
@WebServlet("/GetData")
public class GetData extends HttpServlet{

    private Connection con = null;
    private String url="jdbc:oracle:thin:@//localhost:1521/XE";
    private String user = "*******";
    private String password = "*********";
    private PreparedStatement pstmt;
    private ResultSet res;
    public void init(ServletConfig config) throws ServletException {
        try {
            DriverManager.registerDriver(new OracleDriver());
            if((con = DriverManager.getConnection(url,user,password)) !=null){

            }else {

            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void destroy() {
        // TODO Auto-generated method stub
        try {
            if(con != null) {
                con.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,FileNotFoundException {
        // TODO Auto-generated method stub

        setAccessControlHeaders(response);
        StringBuilder sb = new StringBuilder();
        BufferedReader br = request.getReader();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        JSONObject jObj;

        String usn = null;
        try {
            jObj = new JSONObject(sb.toString());
            usn = jObj.getString("usn");
            System.out.println(usn);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            String s1="SELECT * FROM STUDENT WHERE usn=?";
            pstmt = con.prepareStatement(s1);
            pstmt.setString(1, usn);
            res=pstmt.executeQuery();
            while(res.next() == true) {
                String temp1=res.getString(1);
                String temp2=res.getString(2);
                int m1 = res.getInt(3);
                int m2 = res.getInt(4);
                int m3 = res.getInt(5);

                PrintWriter pw = response.getWriter();
                pw.println("Connection Established");
                pw.println(temp1);
                pw.println(temp2);
                pw.println(m1);
                pw.println(m2);
                pw.println(m3);
                response.setContentType("text/html");
                PrintWriter out = response.getWriter();
                out.write("Found User");
                out.flush();
                out.close();
                System.out.println(temp1+ " "+temp2+ " "+m1+ " "+m2+ " "+m3);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    private void setAccessControlHeaders(HttpServletResponse response) {
        // TODO Auto-generated method stub
         response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token");
    }
}
Access to XMLHttpRequest at 
'http://localhost:9090/AngularFetchData/GetData' from origin 
'http://localhost:4200' has been blocked by CORS policy: 

Response to preflight request doesn't pass access control check: 
  No 'Access-Control-Allow-Origin' header is present on the requested resource.

core.js:9110 ERROR HttpErrorResponse 
{
    headers: HttpHeaders, 
    status: 0, 
    statusText: "Unknown Error", 
    url: "http://localhost:9090/AngularFetchData/GetData", 
    ok: false,
    …
}

共有1个答案

林富
2023-03-14

我也有类似的情况,用下面的配置修复了它。以相对于package.json的角度创建proxy.conf.json文件。向其添加以下代码:/api,添加泛型路径。

{
    "/api": {
    "target": "http://localhost:8080",
    "secure:": false
    }
}

在package.json中,脚本:{start:“ng serve--proxy-config proxy.conf.json”,“build”:“ng build--base-href=\”./\“

添加此配置并运行angular服务器。让我知道如果它工作,你得到任何错误。

 类似资料:
  • 我有一个Android、Ios和web应用程序,它使用php作为后端。所有Api在android和ios中都运行良好,但在web中抛出CORS错误。得到这样的错误 访问位于“”的XMLHttpRequesthttps://example.com/api“起源”http://localhost:49168'已被CORS策略阻止:请求的资源上不存在'Access Control Allow Origi

  • ... 我在Java Spring Boot后端中使用了以下符号: 这是一个错误,我得到:

  • 我正在使用Spring MVC和角7创建一个CRUD应用程序。我在我的Spring应用程序中允许CORS,但是当我从角调用PUT请求时,我得到一个“从源'http://localhost:4200'在'http://localhost:8080/BookAPI/api/updateBook/70'处访问XMLHttpRequest已被CORS策略阻止:对预飞行请求的响应未通过权限改造检查:请求的资

  • 有点晚了,但我记得我最终通过在后端的配置中设置来解决这个问题。 完全偶然地,我注意到如果我在前端的客户端中设置,一切都正常工作。然而,将其切换到不断抛出错误。然后我把两个和两个放在一起,在后端设置,一切都按预期工作。 我的应用程序使用cookie,所以必须这样做。 这可能是重复的,但我没有找到与我的问题相关的线索。 我正在进行以下API调用: 这会引发一个错误: 当我将我的应用程序部署到Herok

  • 我了解了Firebase托管的标头配置,所以我这样做了: 在app中,在didChangeDependencies中有一个简单的firebase初始化,带有所需的数据。然后firebase auth . instance . signinwithemailandpassword(...)关于index.html的一段关于火垒的话: 我在Chrome中测试过很多次,总是失败。只有在localhost

  • 调用JSON时发生此错误。我不知道为什么会发生这个错误。 错误: