Enable CORS AngularJS to send HTTP POST request

Deadly 提交于 2019-11-28 09:05:29

That's how I do CORS in express applications, you have to remember about OPTIONS because for some frameworks there are 2 calls for CORS, first one is OPTIONS which checks what methods are available and then there is actual call, OPTIONS require just empty answer 200 OK

js

allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  if ('OPTIONS' === req.method) {
    res.send(200);
  } else {
    next();
  }
};

app.use(allowCrossDomain);

I have been struggled for a long time to achieve this, finally I got a solution for this now.

You can achieve same thing on server side instead of messing around client side. Here is the simple CORS Filter you need to add on server side.

package com.domain.corsFilter;

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}

Note: If you need help with imports for above, visit the below page topic: Filter requests for CORS Filter requests for CORS

Add this filter in your web.xml

filter
    filter-name corsFilter filter-name
    filter-class com.domain.corsFilter.SimpleCORSFilter filter-class
filter
filter-mapping
    filter-name corsFilter filter-name
    url-pattern /* url-pattern
filter-mapping

Add '<', '/>' tags in web.xml code, I had to remove to post this comment.

Dilhan Jayathilake

Adding content-type header to following fixed the problem for me.

headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
Chanchal Rajbanshi

You just have to add some header properties in your server side response header.

Here is an example for NodeJS server

app.all("/api/*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
  return next();
});

It will solve AngularJS cross-domain AJAX call.

I have found this solution from How to enable CORS in AngularJs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!