相关文章推荐

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Summary

I'm making a GET request to 4chan's API for retrieving threads from a board. This is my code:

const board = this.props.routeParams.tag;
var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
axios.get('https://a.4cdn.org/' + board + '/threads.json', config)
    .then(function (response) {
        console.log(response.data);

I receive the following warning:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
As seen above, I have added the relevant header, but it does not solve the issue. I made the same request from my terminal using cURL and it worked fine.

Context

  • axios version: e.g.: v0.16.0
  • Environment: e.g.: node v6.9.4, Firefox 51.0.1, Ubuntu 14.04
  • joshuakcockrell, Qwertie-, kparlar, sakshichahal53, agiUnderground, fatfish516, hifenhur, unckleg, ngrt, kyleshovbb, and 61 more reacted with thumbs up emoji hifenhur, ChpokmanKG, bbf6, and tilaklodha reacted with hooray emoji joshuakcockrell, yurkagon, Rebaiahmed, flerko, greggx-v1, ErikCupal, angeldelacruzdev, JoseCage, Zalasanjay, vlad909, and 10 more reacted with confused emoji hifenhur, Zalasanjay, JanWalsh91, ChpokmanKG, and bbf6 reacted with heart emoji muminy, HowardRoarkGeek, Zalasanjay, dggit, ChpokmanKG, pgravelin, bbf6, and Mohammed-Mamoun98 reacted with rocket emoji patricklegros, jmailey, and aditya-mitra reacted with eyes emoji All reactions

    cURL does not enforce CORS rules. Those rules are enforced by browsers for security purposes.

    When you mention that you added the relevant header, I assume you mean you added those headers to the request. Actually, the header is expected in the response headers from the server, indicating that the resource is allowed to be accessed by other websites directly.

    FYI, CORS - Cross Origin Resource Sharing. Since your API does not support it, you have two options -

  • Use a proxy server on the same domain as your webpage to access 4chan's API or,
  • Use a proxy server on any other domain, but modify the response to include the necessary headers.
  • I'd like to vote to close this issue as "Not an issue".

    saihgal, ezplora, pete-watters, jiaqiu-09, uldren, aOcOa, crownbackend, snawaz, christopherclemmons, adl1995, and 3 more reacted with thumbs up emoji Goran-S, Fafnir123, bbf6, ledugani, SabrinaDanielle, ElephantBombay, sheecegardezi, csabagabor, Oswalman, xFranklinx, and 24 more reacted with thumbs down emoji nekopipi, thaisfaria, JoseCage, vik80sh, UmarBaig2017, kallaway, snawaz, and bonscotty reacted with heart emoji All reactions

    Thank you for the suggestion. I have updated my code to route the request through a proxy:

    axios.get('https://a.4cdn.org/a/threads.json', {
    	headers: {
    	  'Access-Control-Allow-Origin': '*',
    	proxy: {
    	  host: '104.236.174.88',
    	  port: 3128
    	}).then(function (response) {
    		console.log('response is : ' + response.data);
    	}).catch(function (error) {
    		if (error.response) {
    		  console.log(error.response.headers);
    		else if (error.request) {
    	      console.log(error.request);
    		else {
    		  console.log(error.message);
    	console.log(error.config);
    

    However, I'm still getting this error:

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://boards.4chan.org’).

    I have searched through various forums and questions on Stack Overflow and I can't seem to find any solution to this. It would be appreciated if someone could provide some insight.

    GeorgePlukov, HamzaAnis, davepadrinotera, akhilaudable, fadilnatakusumah, PedroFerr, kareemkibue, reducio, ehsunshahid, tygas, and 50 more reacted with thumbs up emoji dheerajvs, DonavanMartin, DarkPurple141, aqeeljaved88, ritstar, gwanhyeon, quasibit-wrangler, slavafomin, david-popa, ArielGatica, and 3 more reacted with thumbs down emoji All reactions nickensoul, csknk, adl1995, Peakdrum, adexphem, alterhu2020, pbeschetnov, Salec, GanchoDanailov, danidb, and 176 more reacted with thumbs up emoji jakubinformatics and yang6020 reacted with thumbs down emoji jakubinformatics, moahmed123, peymandavoodi, Kitanga, quasibit-wrangler, bbf6, ereztdev, eclairAB, and m0ham4d reacted with laugh emoji ephemeralin and csabagabor reacted with hooray emoji davepadrinotera, harlig, vanyakosmos, Rmalnoult, jillztom, jfcorsini, sekunho, joshuakcockrell, johnworthley, exapsy, and 14 more reacted with confused emoji gabrielberthier, ereztdev, atxy2k, geniuskouta, and m0ham4d reacted with eyes emoji All reactions

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://boards.4chan.org’).

    This is because https://a.4cdn.org and https://boards.4chan.org are considered to be different domains. The difference is in a and boards

    hackel, nccurry, gregholst, JoseCage, bullishgopher, svrakata, thau0x01, slavafomin, juanigaray, and nikhilknoldus reacted with laugh emoji bullishgopher, quasibit-wrangler, and ramyareye reacted with rocket emoji macgari, ritstar, JoseCage, bullishgopher, aemeri, quasibit-wrangler, nosachamos, gabriel3iri, and Snouzy reacted with eyes emoji All reactions

    As a temporary solution you can use this : https://chrome.google.com/webstore/detail/cors-toggle/omcncfnpmcabckcddookmnajignpffnh

    I did not find anything better for now ..

    emileber, oliveirasWell, aamirr216, femilofin, d2phap, saikrishnakethan, girardiricardo, Momjo, javialcantaras, vinolove, and 146 more reacted with thumbs down emoji jdleo, dendihandian, mtunyk, justcode-kr, slavafomin, and ahmeds63 reacted with confused emoji devtechvalens, rsha256, antoniors, NikolasMelui, negative0, thau0x01, WhiteBookmark, kamilbolka, randyhamzahh, luke-sawdays, and Trollgon reacted with eyes emoji All reactions SuperManifolds, squallleonharts, RKuntyi, ecklf, ashfaqnisar, dongron, jessestuart, Nyatra, alim1496, laneschmidt, and 25 more reacted with thumbs down emoji CAPJackie, slavafomin, merhawie, eclairAB, koko1313, ico85, and JivkoJelev91 reacted with laugh emoji All reactions emileber, agata-anastazja, axolotl, johannesmols, jraleman, amustapha, davek1979, gfpalacios, Baltimer, SuperManifolds, and 35 more reacted with thumbs up emoji quasibit-wrangler, nilay-patel-9spl, and hirokihokari reacted with thumbs down emoji All reactions

    Access-Control-Allow-Origin is a response header, not request header:
    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

    axios.get(url, { headers: {'Access-Control-Allow-Origin': *} } ) means nothing!

    axios.get(url, { crossdomain: true })

    seungha-kim, teleyinex, mikeynova, sin-tanaka, robertlagrant, techchrism, heshamelmasry77, Avkash, ffpetrovic, dambrogia, and 84 more reacted with thumbs up emoji tinoweb, RandomlyOnside, ducdev, ahmaxed, oscarg798, hatai, etdte, u-kan, chl03ks, camerican, and 321 more reacted with thumbs down emoji zaguerinho, nb256, wangyu0426, MANDA-LAWINE, mvochoa, JoseCage, bruunas, jonmarcello, Passarella, cwiz, and 6 more reacted with hooray emoji mtgofa, StellaRakoto, vishwasnavadak, sugoikondo, zaguerinho, nb256, uniorder, yashSrijan, smisevski, CristalT, and 16 more reacted with heart emoji rickrribeiro, hafizmmehmood, asahitarou, bruunas, mukete, andrew1337, a-j-n, lcaa92, and icarodemorais reacted with rocket emoji Daniela0106, eml-nx, and gost1k reacted with eyes emoji All reactions TrayHard, tugi93, sathiz, Seanitzel, stevengrimaldo, chgsilva, rajavijayach, rlscode, besideL, Adyel, and 60 more reacted with thumbs up emoji Daniela0106 reacted with thumbs down emoji All reactions

    The remote service to which you are making your AJAX request does not accept cross origin AJAX requests from your domain. One thing you could do if you have access to your website server-side codebase, is to create a controller action there (assuming you are using an MVC) and then use it to consume the remote service. You can then make AJAX requests to your controller action. A bonus to this approach is that you could run additional checks before contacting the remote service, formatting its response and even caching it.

    Salec, techchrism, DarkPurple141, slushnys, ronnin, GeorgeBills, slavafomin, and alexcurtui reacted with thumbs up emoji wdews, quangthe, biopowder, suTCS, Gadzev, mrgenco, benskyio, leo1mml, ajmeese7, o1lab, and 168 more reacted with thumbs down emoji All reactions akhilaudable, Paelsis, ahmaxed, lethalskillzz, xkortex, shenlin192, EmaSuriano, TaroWong, asher23, Gadzev, and 131 more reacted with thumbs up emoji xurshid29, bbf6, sarangnx, and aditya-mitra reacted with laugh emoji themperament and bbf6 reacted with hooray emoji All reactions JohnAlston11, seafoam6, alejo4373, diegoraian, jameslinjl, MaleDeer, iAminaDarwish, lupangsogood, alim1496, rahul-satal, and 6 more reacted with thumbs up emoji VIRGO96, Hansel03, juanigaray, and jrotoni reacted with thumbs down emoji rahul-satal, spwinner2017, Spixz, Tactful-biao, EmersonOlvr, frontendkris, and nvinayvarma189 reacted with laugh emoji spwinner2017, juanigaray, and ashkan-esz reacted with confused emoji wpitallo, lopezdp, and acquirenaren reacted with eyes emoji All reactions

    Normally this would work, but in the case that it doesn't and you don't have any access to that domain...

    axios.get('https://www.notmydomain.com/1511.json')
        .then(function (response) {
            console.log(response.data);
    

    What I did was create a repeater on my server

    axios.get('https://www.mydomain.com/repeater.php?url=https://www.notmydomain.com/1511.json')
        .then(function (response) {
            console.log(response.data);
    
    /* repeater.php */
    function collect_data($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //remove on upload
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, false);
        curl_setopt($ch, CURLOPT_REFERER, "https://www.notmydomain.com");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $result = curl_exec($ch);
        echo curl_error($ch);
        curl_close($ch);
    return($result);
    echo collect_data($_GET["url"]);
      n1lsan, KingZee, LizAinslie, Gelbotron, jeremycharlesgillespie, emilenriquez, MukarramAli1729, heregoesnoth, cassmtnr, VassilisPallas, and 41 more reacted with thumbs down emoji
      mzalazar, matass, jongbonga, and veloso14 reacted with laugh emoji
      GrolaElmahdi, slavafomin, drinkingjava, Blunderchips, olexandrbig, and michaelkoder reacted with confused emoji
        All reactions
              

    The server needs to respond with CORS headers on the options call. If you are using nodejs/express, you can fix this for all endpoints with:

    app.use(function(req, res, next) {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      next();
    

    But that's a little loose. Probably want to tighten up for production.

    gasner, MonaTem, Loubot, Delagardi, hookom, johnworthley, MateusLehmkuhl, zhangzhhz, Pazaz, sharelookapp, and 50 more reacted with thumbs up emoji vgjenks, joshuakcockrell, nguyentrongduy, autohub7, ddcech, tusharchutani, TrayHard, stevengrimaldo, Omar-Bsoul, unckleg, and 10 more reacted with thumbs down emoji igormcsouza, ntucakovic, arkarmintun1, m0ham4d, and RichelmyLopes reacted with laugh emoji EastJesus, antoniotex, olgagret3, OeMA4, JoseCage, luiz-albertoni, muthu1712, mzalazar, m0ham4d, HelloooLucas, and 3 more reacted with hooray emoji vgjenks, Alex85651, amirhh, samuelterra22, stevengrimaldo, ritstar, xt9, and jmohler1970 reacted with confused emoji Nderim1, YaroslavGrushko, nikoada, amirashawky, EastJesus, antoniotex, olgagret3, OeMA4, jimvdl, djom202, and 10 more reacted with heart emoji m0ham4d, HelloooLucas, suaebahmed, RichelmyLopes, mahdipakravan-dev, aronbergman, andreataglia, and skashi reacted with rocket emoji All reactions

    I have long solved that problem though. The server belongs to a 3p service and therefore out of my control. I simply proxied it instead. All is well on that front.

    Thanks

    TaroWong, fadilnatakusumah, markwalet, Gadzev, CallumSeymour, spartanhero93, cyberena, alim1496, and gabriel3iri reacted with thumbs up emoji gabriel3iri reacted with eyes emoji All reactions ayu93, TrayHard, Seanitzel, rajavijayach, Jaccccccccccccccccccccccccccccck, OmerUygurOzer, schoettler, imbudhiraja, baumannzone, SuperManifolds, and 21 more reacted with thumbs up emoji dayhaysoos, nctruong, kennCK, way2datta, vongvisalsambath, lexcode, Georgian, hasnatbabur, sultan99, makeconstnotvar, and 68 more reacted with laugh emoji tehSLy and RobertBroersma reacted with confused emoji gabriel3iri reacted with eyes emoji All reactions ScottGibsonEmpire, unckleg, alpenist, SuperManifolds, aacassandra, luciagirasoles, jwhittle933, and towry reacted with thumbs up emoji samrap, PoliakovMaksymZfort, raoulj, ajmeese7, kyfk, gagan-bansal, Djiggy, Mehdi-Hp, FMGordillo, bayboraoren, and 41 more reacted with thumbs down emoji wilbertverayin, vinhnguyen1211, IngIeoAndSpare, sekunho, currymich, bayboraoren, jrejaud, CMarzin, FrenchMajesty, joshuakcockrell, and 30 more reacted with laugh emoji joshuakcockrell, Pkmmte, khalidahmada, MathieuDelafosse, patientplatypus, Jaccccccccccccccccccccccccccccck, and aacassandra reacted with hooray emoji wa05, juanigaray, and pedro-cerdera reacted with confused emoji All reactions

    The problem isnot axios, but the API that you're requesting !

    For example I was coded an API in Flask and the GET method was:

    @app.route('/api/autores', methods=['GET'])
    def get_users():
        drivers_json = []
        for user in user_dao.list_users():
            drivers_json.append(user.to_json())
        return make_response(jsonify(drivers_json), 201)
    

    But the problem was solved when I add a header in API response:

    @app.route('/api/autores', methods=['GET'])
    def get_users():
        drivers_json = []
        for user in user_dao.list_users():
            drivers_json.append(user.to_json())
        response = jsonify(drivers_json)
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    

    Then I log my axios response and I get it:

    {data: Array(4), status: 200, statusText: "OK", headers: {…}, config: {…}, …}

    I dont know what API you all are using but in Flask It was solved !

    I don't think you can resolve CORS directly in axios, because CORS is a browser restriction which is between your browser and target servers.

    You can either:

  • Include Access-Control-Allow-Origin in your response headers from your target server.
  • Do not include hostname in your axios request so it will request your original server. Then from your original server you can do whatever you want to the target server.
  • This is not the issue with the axios This is the issue with the backend. I am using Django. And adding these two will solve the issue.

    Add CORS Middlewear

    MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    

    And allowing the CORS.
    (Allowing CORS for all)

    CORS_ORIGIN_ALLOW_ALL = True
    

    (This is a bit insecure as it allows all origins. Which will make it vulnurable for CSRF attacks)
    Hence for production allow only for Specific origins

    CORS_ORIGIN_ALLOW_ALL = False
    CORS_ORIGIN_WHITELIST = (
        '<YOUR_DOMAIN>[:PORT]',
    

    Example 👍

    CORS_ORIGIN_ALLOW_ALL = False
    CORS_ORIGIN_WHITELIST = (
        '127.0.0.1:8000',
              

    For those still struggling:
    Hopefully by now you understand that this isn't an issue with Axios and the browser is blocking CORS because of a header not being set by the server. If you do understand this and are still having trouble with your own server not setting the headers be sure to set it on your actual web server when using a reverse proxy. For instance, many Node/Express apps are served by NGINX in production with a reverse proxy. See enable-cors.org for how to set it in NGINX.

    For those still struggling:
    Hopefully by now you understand that this isn't an issue with Axios and the browser is blocking CORS because of a header not being set by the server. If you do understand this and are still having trouble with your own server not setting the headers be sure to set it on your actual web server when using a reverse proxy. For instance, many Node/Express apps are served by NGINX in production with a reverse proxy. See enable-cors.org for how to set it in NGINX.

    I have been struggle 3 hours, nothing change on client side, finally I added the following stuff on server:

    install egg-cors ( for egg project only)

    // ./config/config.default.js
    config.cors = {
        origin: ["http://localhost:8080"],
        allowedHeaders: [
          "Content-Type",
          "Authorization",
          "Access-Control-Allow-Methods",
          "Access-Control-Request-Headers"
        credentials: true,
        enablePreflight: true
    

    that's all

    const board = this.props.routeParams.tag;
    axios.get('https://cors-anywhere.herokuapp.com/' + 'https://a.4cdn.org/' + board + '/threads.json', config)
    .then(function (response) {
    console.log(response.data);

    Just use fetch to test if server's cors works first.

    And...

    axios can request my koa-server, but not iris directly, both of them arms popular cors-middleware.

    #1358

    This worked for me and need to learn why

    I was Working with Tornado and Vuejs, axios was not the problem, on my backend aded:

    # Tornado
    class ClassName(tornado.web.RequestHandler):
        def set_default_headers(self):
            self.set_header("Content-Type", "application/json")
            self.set_header("Access-Control-Allow-Origin", "*")
            self.set_header("Access-Control-Allow-Headers", "content-type")
            self.set_header(
                'Access-Control-Allow-Methods',
                'POST, GET, OPTIONS, PATCH, PUT'
    Getting this error
    Access to XMLHttpRequest at 'http://localhost:4000/users' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    Could anyone give me step by step solution to what I should do ?

    @albertpinto look at all the possible solutions in this mega thread. It's not a client-side/front-end issue on your end - it is in fact the server (localhost:4000). The server needs to respond with CORS headers to allow the origin.

    For example, your server should reply with headers such as:

    Access-Control-Allow-Origin:  *
    Access-Control-Allow-Headers: Content-Type
              

    I solved this by the following :

  • Install cors npm : npm install cors (on your rest node server in my case http://localhost:4000)
  • This also goes on your end point:
    var cors = require('cors')
    var express = require('express')
    var cors = require('cors')
    var app = express()
    app.use(cors())

    Thanks for all the suggestions!

    // For CORS, if you use express js, you can simply use cors package via npm.

    app.use(
        cors({
            credentials: true,
            origin: [
                'http://localhost:8080',
                'http://your-production-website.com'
        }),
    

    cURL does not enforce CORS rules. Those rules are enforced by browsers for security purposes.

    When you mention that you added the relevant header, I assume you mean you added those headers to the request. Actually, the header is expected in the response headers from the server, indicating that the resource is allowed to be accessed by other websites directly.

    FYI, CORS - Cross Origin Resource Sharing. Since your API does not support it, you have two options -

  • Use a proxy server on the same domain as your webpage to access 4chan's API or,
  • Use a proxy server on any other domain, but modify the response to include the necessary headers.
  • I'd like to vote to close this issue as "Not an issue".

    @sunnykgupta
    same logic, same body, but angular http post request to remote backend endpoint does not receive CORS block error

    If you're having a Go server running, suggest you to use Gorilla

    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
    originsOk := handlers.AllowedOrigins([]string{"*"})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})
    err := http.ListenAndServe("localhost:8081", handlers.CORS(originsOk, headersOk, methodsOk)(r))
              

    I solved this by the following :

    1.create a vue.config.js file in the root of the project right beside package.json, containing:

    module.exports = {
        devServer:{
            proxy: {
                '/apiv1': {
                    target: 'https://fuping.site/',
                    changeOrigin: true,
                    pathRewrite: {
                        '^/apiv1': ''
    

    2.make a http request like this:

    this.$axios({
              method:'get',
              url:'apiv1/about/',
            }).then(function(response){
              console.log(response.data)
            }).catch(error=>{
              console.log(error)
              

    axios.get('https://a.4cdn.org/a/threads.json', {
    headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    proxy: {
    host: '104.236.174.88',
    port: 3128
    }).then(function (response) {
    console.log('response is : ' + response.data);
    }).catch(function (error) {
    if (error.response) {
    console.log(error.response.headers);
    else if (error.request) {
    console.log(error.request);
    else {
    console.log(error.message);
    console.log(error.config);

    Hello everyone,
    I am just posting this as it took hours for me to solve this.

    First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The problem started when I started using axios with my custom instance.

    In my case, it was a very specific problem when we use a baseURL in axios instance and then try to make GET or POST calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.

    In general, the pre-flight OPTIONS request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.

    I hope this might help someone although none of it is a bug.

     
    推荐文章