我想将角度为4的数据发送到javaservlet(跨域) [英] I want to send data with angular 4 to javaservlet (cross-domain)

查看:68
本文介绍了我想将角度为4的数据发送到javaservlet(跨域)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将角度为4的数据发送到Java Servlet,但由于未通过访问控制而无法发送.我想使用Java servlet将数据插入db

I want to send data form angular 4 to java servlet but I can't send because doesn't pass access control. I want to insert data to db with java servlet

这是我的代码 前端:data.service.ts

this my code front-end: data.service.ts

 import { Injectable } from '@angular/core';
 import { Http, Response } from '@angular/http';
 import { Headers, RequestOptions, ResponseOptions } from '@angular/http';
 import { Observable } from 'rxjs';
 import 'rxjs/add/operator/map';
 import 'rxjs/add/operator/toPromise';

 @Injectable()
 export class DataService {

 result: any;
 private url = '//localhost:8080/my-java-web/';
 constructor(private _http: Http) { }


 addBookWithPromise(user: object): Promise<object> {
  const headers = new Headers({ 'Content-Type': 'application/json', 
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods":" GET, POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type",
  "Access-Control-Allow-Credentials": "true"});
  const options = new ResponseOptions({ headers: headers });
  return this._http.post(this.url + 'loginsuccess', user, 
   options).toPromise()
  .then(this.extractData)
  .catch(this.handleErrorPromise);
  }

  private extractData(res: Response) {
  const body = res.json();
   return body.data || {};
   }
   private handleErrorObservable (error: Response | any) {
    console.error(error.message || error);
   return Observable.throw(error.message || error);
   }
   private handleErrorPromise (error: Response | any) {
   console.error(error.message || error);
   return Promise.reject(error.message || error);
   }

    }

后端:java servlet

backend: java servlet

public class LoginSuccess extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Access-Control-Allow-Origin","*");
    response.addHeader("Access-Control-Allow-Methods"," GET, POST, OPTIONS");
    response.addHeader("Access-Control-Allow-Headers","Content-Type");
    response.addHeader("Access-Control-Allow-Credentials", "true");
    PrintWriter out = response.getWriter();

    String username = request.getParameter("username");
    String password = request.getParameter("password");



    System.out.println("Success" +username);

非常感谢

推荐答案

您需要阅读CORS协议. 我写了博客帖子前一段时间,实施CORS.它基于使用Spring框架(特别是Spring Boot),而不是直接使用Servlet API,但是它确实对CORS的工作方式有相当广泛的解释.

You'll need to read up on the CORS protocol. I wrote a blog post a while back about implementing CORS. It's based on the use of the Spring framework (specifically Spring Boot), not the Servlet API directly, but it does have a fairly extensive explanation of how CORS works.

您的特定问题是您仅处理POST. CORS协议涉及Web浏览器向您的服务器发出OPTIONS请求.

Your specific problem is that you are only handling POSTs. The CORS protocol involves the web browser making an OPTIONS request to your server.

此OPTIONS请求必须具有响应中返回的Access-Control-Allow-Origin和相关标头.

It is this OPTIONS request that must have the Access-Control-Allow-Origin and related headers returned in the response.

如果浏览器在响应中看到这些标头,则它将执行POST.

If the browser sees those headers in the response, it will then do the POST.

如果在对OPTIONS请求的响应中未看到这些标头,则将收到HTTP错误,显示类似在请求的资源上不存在'Access-Control-Allow-Origin'标头"之类的内容,并且POST请求将不会发出.

If it does not see those headers in the response to the OPTIONS request, you'll get an HTTP error, reading something like "No 'Access-Control-Allow-Origin' header is present on the requested resource", and the POST request will not be made.

这篇关于我想将角度为4的数据发送到javaservlet(跨域)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆