0

This is my Html page

<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>

This is my Component file:

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);
      });
  }
}

This is my Servlet

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");
    }
}

please help me with this code I have tried a lot but it gives me the same error all the time it says that due to cors policy you request has been bloacked here is the exact error,

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,
    …
}
Dushyant Tankariya
  • 1,432
  • 3
  • 11
  • 17
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than an 200 OK success response? – sideshowbarker Oct 08 '19 at 14:42
  • response 200 ok success – Karanrajsinh Jadeja Oct 08 '19 at 15:18
  • OK then the problem appears to be that your servlet code isn’t adding the Access-Control-\* response headers to OPTIONS responses. The code shown in the question seems to be only adding those headers to POST responses. The reason you need to send those headers in OPTIONS responses is that your browser automatically on its own sends a CORS preflight OPTIONS request before trying the POST request from your frontend code. – sideshowbarker Oct 08 '19 at 15:23
  • Gettig this error now Access to XMLHttpRequest at 'http://localhost:9090/AngularFetchData/GetData' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. – Karanrajsinh Jadeja Oct 08 '19 at 15:36
  • Remove the entire `this.headers = new HttpHeaders` block from your frontend code (component file). The Access-Control-Allow-\* headers are all response headers, not request headers. The new problem you mention in your comment is due to your frontend code trying to add Access-Control-Allow-Origin as a request header. – sideshowbarker Oct 08 '19 at 15:56
  • So you are saying i am not supposed to add any headers? but then i will be back to the same initial problem. Please if possible tell me what should i update in the above code and where exactly – Karanrajsinh Jadeja Oct 08 '19 at 16:13

1 Answers1

-1

I had a similar situation, fixed it with below configuration. create proxy.conf.json file in angular relative to package.json. add below code to it: /api, add your generic path.

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

In package.json, scripts: { start: "ng serve --proxy-config proxy.conf.json", "build": "ng build --base-href=\"./\""

Add this configuration and run the angular server. Let me know if it works and you are getting any error.

Vipul
  • 545
  • 1
  • 8
  • 30