Как я могу сделать Cross-Origin в скрипте приложения Google? - PullRequest
0 голосов
/ 30 сентября 2018

Я пробовал несколько учебных пособий, но ничего не получалось.

Моя проблема заключается в следующем: если я нажимаю на ссылку html, она открывает другую страницу, но если я пытаюсь открыть через форму, она всегда показывает перекрестныйОшибка источника.

Я предоставляю публичную ссылку с копией главных страниц моего проекта.Может кто-нибудь показать мне на практике, как решить эту проблему?

Проект:

doGet.gs

function doGet(e) {
  if(!e.parameter.page){
    //When no specific page requested and no session or the page is not to register, return Login page;
    return(HtmlService.createTemplateFromFile('page').evaluate()
           .setTitle('Page 1')
           .setSandboxMode(HtmlService.SandboxMode.IFRAME)
          );
  } else {
    //Use page parameter to pick an html file from the script;
    return(HtmlService.createTemplateFromFile(e.parameter['page']).evaluate()
           .setTitle(e.parameter['title'])
           .setSandboxMode(HtmlService.SandboxMode.IFRAME)
          );
  }
}

/*==================== That code goes include files in the page. ====================*/
function include(filename) {
  return(HtmlService.createHtmlOutputFromFile(filename)
         .setSandboxMode(HtmlService.SandboxMode.IFRAME)
         .getContent()
        );
}

/*==================== Get the URL for the Google Apps Script running as a WebApp. ====================*/
function getScriptUrl(){
  var url = ScriptApp.getService().getUrl();
  return(url);
}

javaScript.html

<script>
/*==================== Attach a submit handler to the form. ====================*/
$("[name='loginForm']").submit(function(event){
  var $form;
  var login;
  var url;

  //Stop form from submitting normally.
  event.preventDefault();

  //Get some values from elements on the page:
  $form = $(this);
  login = {};

  login.email = $form.find("#inputUser").val();
  login.senha = $form.find("#inputPassword").val();
  url = $form.attr("action");

  var posting = $.post(url, login);

  //Post sucess.
  posting.done(function(data){
    console.log(data);

    //Redirect to page2.
    //var geting = $.get(url, login);
  });
});

/*==================== Get app url. ====================*/
$(function() {
  google.script.run.withSuccessHandler(setHref)
    .getScriptUrl();
});

/*==================== Modifying link of navbar. ====================*/
function setHref(url){
  var links = $("a[href], form[action]");

  for(var i = 0; i < links.length; i++){
    var page;

    if(links[i].tagName == "A"){
      page = links[i].getAttributeNode("href").value;
      links[i].getAttributeNode("href").value = url + page;
    } else {
      page = links[i].getAttributeNode("action").value;
      links[i].getAttributeNode("action").value = url + page;
    }
  }
}
</script>

Страница

<!DOCTYPE html>
<html lang="pt-br">
  <head>
  </head>
  <body>
    <form name="loginForm" action="?page=page2&title='Page 2'" method="POST">
      <input type="text" id="inputUser" name="inputUser" value=""/>
      <svg height="10" width="10">
      <path d="M4 0c-1.105 0-2 1.119-2 2.5s.895 2.5 2 2.5 2-1.119 2-2.5-.895-2.5-2-2.5zm-2.094 5c-1.07.04-1.906.92-1.906
      2v1h8v-1c0-1.08-.836-1.96-1.906-2-.54.61-1.284 1-2.094 1-.81 0-1.554-.39-2.094-1z" id="person"></path>
      </svg>
      Usuário
      <input type="password" id="inputPassword" name="inputPassword" value=""/>
      <svg height="10" width="10">
      <path d="M5.5 0c-1.38 0-2.5 1.12-2.5 2.5 0 .16.033.297.063.438l-3.063 3.063v2h3v-2h2v-1l.063-.063c.14.03.277.063.438.063
      1.38 0 2.5-1.12 2.5-2.5s-1.12-2.5-2.5-2.5zm.5 1c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1z" id="key"></path>
      </svg>
      Senha
      <button type="submit">Login</button>
    </form>

    <!-- ================================================== -->
    <!-- jQuery -->
    <?!= include('jQuery'); ?>
    <!-- Standard JavaScript -->
    <?!= include('javaScript'); ?>
  </body>
</html>

doPost

function doPost(e){
  var callback;
  var output;
  var data;

  data.e = e;
  data.url = getScriptUrl();

  //Returning the response to the application.
  callback = e.parameter.callback;
  output  = ContentService.createTextOutput();

  if (callback === undefined) {
    output.setContent(JSON.stringify(data));
  } else {
    output.setContent(callback + "(" + JSON.stringify(data) + ")");
  }

  output.setMimeType(ContentService.MimeType.JSON);

  return(output);
}

page2

<!DOCTYPE html>
<html lang="pt-br">
  <head>
  </head>
  <body>
    <div id="result">
    </div>

    <!-- ================================================== -->
    <!-- jQuery -->
    <?!= include('jQuery'); ?>
    <!-- Standard JavaScript -->
    <?!= include('javaScript'); ?>
  </body>
</html>

Эта ошибка возникает, когда я щелкаю, чтобы отправить форму, в функции отправки в JavaScript.html

Не удалось загрузить https://script.google.com/macros/s/AKfycbyzqu-axemMxSmafZdEpqu1uYssWMM9SAleKzmPB_Tu-0rF8vnk/exec?page=page2&title=%27Page%202%27: Нет заголовка 'Access-Control-Allow-Origin' в запрашиваемом ресурсе.Origin 'https://n -iqrbuxm45ga265etahrrml6j6klncaly5mdwd3y-0lu-script.googleusercontent.com ' поэтому доступ запрещен.

...