AngularJS,Google Chrome浏览器阻止我的应用发出发布请求,需要添加标题的帮助 [英] AngularJS, Google Chrome preventing my app to make post requests, need help adding headers

查看:99
本文介绍了AngularJS,Google Chrome浏览器阻止我的应用发出发布请求,需要添加标题的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般对AngularJS,API和编码都是陌生的。我创建了这个AngularJS应用,让用户向我创建的API发出发布请求。这是一个简单的括号检查器,并且一切正常,除了我必须在chrome浏览器中激活CORS插件才能使其正常工作,而我不能要求用户这样做。

I am pretty new to AngularJS, APIs and coding in general. I created this AngularJS app that let's the user make a post request to an API that I have created. It is a simple parenthesis checker, and everything works fine, except that I have to activate the CORS addon in my chrome browser to make it work, which I can not ask users to do.

我很确定这方面有办法解决,但我不太了解。我想我需要在HTTP请求代码中添加一些标头,对吗?

I am pretty sure there is a way around this but I don't really understand it. I think I need to add some headers to my http request code, right?

这是我的angularjs服务发出的请求:

Here is my angularjs service that makes the requests:

function ApiService($http) {
    // API = '//localhost:3000/parentheses';
    API = 'https://parentheses-api.herokuapp.com/parentheses';
    this.getUser = (entry) => {
        // console.log(this.entry);
        return $http
            .post(API, { string: entry} )
            .then(function (response) {
                // console.log(response.data);
                return response.data;
            }, function (reason) {
                // error
            })
        // this.entry = "";
    };
};

angular
    .module('app')
    .service('ApiService', ApiService);

我认为这是我应该添加标题的地方。但是究竟是什么标题呢?

I think this is where I should add the headers. But how and what headers exactly? I don't really get it at this point.

这是一个完整的项目,其中有2个文件夹,一个包含API,另一个包含上面代码所在的APP(ApiService。 js)

Here is the full project with 2 folders, one containing the API and the other containing the APP where the code above is located (ApiService.js)

任何帮助将不胜感激!

推荐答案

如果您要求一个来自其他域的API作为您的前端,那么您的API后端将需要使用正确的CORS标头进行响应。看看: https:/ /developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

If you are requesting an API that is served from a different domain as your frontend, then your API backend will need to respond with the correct CORS headers. Take a look at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

访问控制-Allow-Origin:*

这告诉浏览器允许来自任何来源的请求代码访问您的API。

This tells the browser to allow requesting code from any origin to access your API.

或者,使用 Access-Control-Allow-Origin:< origin> 告诉浏览器仅允许指定的来源访问您的API。

Alternatively, using Access-Control-Allow-Origin: <origin> tells the browser to only allow the origin specified to access your API.

这篇关于AngularJS,Google Chrome浏览器阻止我的应用发出发布请求,需要添加标题的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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