如何使用Angular2向外部API发出POST请求?

时间:2017-01-10 07:19:03

标签: angularjs api angular cors

我正在尝试利用CORS发布帖子请求。我遇到了几篇与 CORS 相关的文章/答案,但不知何故却无法让它发挥作用。

根据我的理解,access-control-allow-origin: *将在服务器端设置以使其正常工作,但我在这里有一个angular-cli项目。

我的项目纯粹基于Angular 2.1,不涉及后端服务器。任何有关如何正确设置的建议都将受到高度赞赏。

我得到的确切错误是:

"NetworkError: 404 Not Found - https://flowxo.com/hooks/a/rbpja7r2/?usertype=User"

并在控制台中显示此警告:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the
remote resource at https://flowxo.com/hooks/a/rbpja7r2/?usertype=User.
(Reason: CORS header 'Access-Control-Allow-Origin' missing).

更新

以下是我尝试发出POST请求的方式:

let headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Methods', 'POST, OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
return this.http.post(
    this.flowxoUrl,
    JSON.stringify(formData),
    {headers: headers}
  )
  .map((res:Response) => res.json())
  .catch((error:any) => Observable.throw(error.json().error || 'Server error')); //...errors if any

1 个答案:

答案 0 :(得分:1)

这是服务器端问题,而不是Angular。

您的服务器应以Access-Control-Allow-Origin标题回复。

Java(Spring)示例:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*"); //you can specify domains here * - is a wildcard, it will allow all origins to request
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type");

        if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {}
}