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

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

问题描述

我想将 angular 4 的数据发送到 java servlet,但我无法发送,因为没有通过访问控制.我想用 java servlet 将数据插入数据库

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.

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

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