如何在我的应用程序中将cookie与请求一起发送到后端

如何在我的应用程序中将cookie与请求一起发送到后端

本文介绍了如何在我的应用程序中将cookie与请求一起发送到后端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ember中是否有一种方法可以将包含请求的cookie发送到后端?

Is there a way in Ember to send cookies with the requests to the backend?

例如:如果我的客户URL是protocol://example.com.当我导航到protocol://example.com/profile时,属于同一域的cookie将在请求标头中.但是,它们不会持久存在于配置文件路由模型方法对protocol://example-host/posts发出的示例的后续请求中.我如何使这些cookie持久化?

For example: if my client URL is protocol://example.com. The cookies that belong to the same domain will be in the request header when I navigate to protocol://example.com/profile. However, they do not persist in the subsequent request/s the profile route model method makes -> example to protocol://example-host/posts. How do I make those cookies persist?

/app/routes/profile.js:

import Ember from "ember";
import AuthenticatedRouteMixin from "simple-auth/mixins/authenticated-route-mixin";

export default Ember.Route.extend({
  model() {
    return this.store.findAll("post");
  },

  renderTemplate() {
    this.render("header", {
      outlet: "header"
    });

    this.render("profile");
  }
});

/app/adapters/application:

import Ember from "ember";
import DS from "ember-data";

export default DS.RESTAdapter.extend({
  host: 'http://example-host.com',
  corsWithCredentials: true,
  crossDomain: true,
  xhrFields: { withCredentials: true }
});

推荐答案

这在我的生产应用中有效. app/adapters/application.js中的代码:

This works in my production app. Code in app/adapters/application.js:

import Ember from 'ember';

$.ajaxSetup({
  xhrFields: {
    withCredentials: true
  }
});

export default DS.RESTAdapter.extend({
  ajax(url, method, hash) {
    hash = hash || {};
    hash.crossDomain = true;
    hash.xhrFields = {
      withCredentials: true
    };
    return this._super(url, method, hash);
  }
})

这篇关于如何在我的应用程序中将cookie与请求一起发送到后端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 19:20