58945

http.post(url, postData, options) does not set header

Question:

I have a problem when use HTTP post method in the following code:

let body = JSON.stringify(applicationLink); let requestHeaders = new Headers(); var headers = new Headers(); headers.set('Content-Type', ['application/json']); headers.set('Access-Control-Allow-Origin', ['*']); let reqoptions = new RequestOptions({ headers: headers }); return this._http.post(this._applicationLinksUrl + this._linkServicePath,body,reqoptions).map(res => res.json())

When I execute the code I see an error:

XMLHttpRequest cannot load http..... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http....' is therefore not allowed access. Request Method:OPTIONS is mde instead of post Request URL:http://localhost:7001/workprocess-service/resources/links Request Method:OPTIONS Status Code:200 OK Remote Address:[::1]:7001 Response Headers view source Allow:OPTIONS,POST,GET,HEAD Content-Type:application/vnd.sun.wadl+xml Date:Thu, 26 May 2016 11:10:25 GMT Last-Modified:Thu, 26 May 2016 09:02:27 CEST Transfer-Encoding:chunked Vary:Accept X-Powered-By:Servlet/3.0 JSP/2.2 Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:access-control-allow-origin, content-type Access-Control-Request-Method:POST Connection:keep-alive Host:localhost:7001 Origin:http.... Referer:http.... User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36

and my data is not linked to the request.

If I remove reqoption

return this._http.post(this._applicationLinksUrl + this._linkServicePath,body).map(res => res.json())

the request is a POST but i receive an error 415 ( Unsupported Media Type)

Request URL:http://localhost:7001/workprocess-service/resources/links Request Method:POST Status Code:415 Unsupported Media Type Remote Address:[::1]:7001 Response Headers view source Connection:close Content-Length:22 Content-Type:text/html; charset=UTF-8 Date:Thu, 26 May 2016 11:14:44 GMT X-Powered-By:Servlet/3.0 JSP/2.2 Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8 Connection:keep-alive Content-Length:48 Content-Type:text/plain;charset=UTF-8 Host:localhost:7001 Origin:http:.... Referer:http:..... User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 Request Payload view source {labelFR: "dsds", labelNL: "dsds", url: "dsds"} labelFR : "dsds" labelNL : "dsds" url : "dsds"

My data is linked to the request

Answer1:

You need to make your server set the header Access-Control-Allow-Origin because you are sending a <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" rel="nofollow">CORS</a> "Cross Origin Resource Sharing" request. Which simply means you are sending the request to a url that's not the same as the url you are sending from.

I see your backend is servlet/3.0, you can enable CORS "for all origins" by adding a web filter

import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; @WebFilter(urlPatterns = {"*"}) public class CORSFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Origin", "*"); chain.doFilter(request, response); } @Override public void destroy() { } }

Recommend

  • Jsoup authentication failed
  • hapi.js Cors Pre-flight not returning Access-Control-Allow-Origin header
  • Add SugarCRM REST services to NetBeans
  • MultivaluedMap exception
  • Save blank file in Objective-C
  • How to redirect user when certain condition is met using REST JAX-RS implementation?
  • JAX-RS file downloads, multiple content types
  • Samsung Nexus S vs HTC - NFC Intent Filter + AAR
  • Working with big files in classic ASP
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • read values from form post in jquery or javascript
  • Can you pass an array from javascript to asp.net mvc controller action without using a form?
  • how to populate a SQLite database and use that database in phonegap?
  • rewrite uppercase url to lowercase url htaccess
  • HttpClient: disabling chunked encoding
  • HttpURLConnection Closing IO Streams
  • PLSQL: Get number of records updated vs inserted when a merge statement is used
  • GAE: Way to get reference to an HttpSession from its ID?
  • How do I configure context broker accept post requests from my remote sensor?
  • saving file generated by TCPDF
  • Eloquent update method change created_at timestamp
  • Jetty 9 HashLoginService
  • Display images in Django
  • Meteor: Do Something On Email Verification Confirmation
  • Get data from AJAX - How to
  • Cannot resolve symbol 'MyApi'
  • How to get address from latitude and longitude android google map v2 [duplicate]
  • FB SDK and cURL: Unknown SSL protocol error in connection to graph.facebook.com:443
  • Java applet as stand-alone Windows application?
  • How to limit post in wp_query
  • AngularJs get employee from factory
  • Acquiring multiple attributes from .xml file in c#
  • Free memory of cv::Mat loaded using FileStorage API
  • using HTMLImports.whenReady not working in chrome
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • How can I remove ASP.NET Designer.cs files?
  • java string with new operator and a literal
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize