通过nuxt js设置cookie时将花括号转换为字符转义码

问题描述 投票:0回答:1

我有两个网页,一个从php运行,另一个从nuxt js运行。我已经从php端设置了cookie,现在我想在nuxt平台上使用和操纵cookie的值,然后再次设置相同的名称。我正在使用cookie-universal-nuxt插件设置cookie。

现在我在这里面临一个问题,即由php设置的cookie如下所示:

{{%22name%22:%22vandana%22%2C%22email%22:%[email protected]%22%2C%22display_city%22:%22Jakarta + Selatan%22%2C%22city%22:%22jakarta- selatan%22%2C%22city_id%22:%22146%22%2C%22subCityId%22:%22%22%2C%22subCityName%22:%22%22%2C%22mobile%22:%22847387483%22%2C% 22alternateMobile%22:%22%22%2C%22lead_type%22:%2270%22%2C%22brandSlug%22:%22toyota%22%2C%22modelSlug%22:%22kijang-innova%22%2C%22variantSlug%22: %22%22%2C%22preferDayDay%22:%227%22%2C%22preferTime%22:%22%22%2C%22purchaseOption%22:%22%22}

和我的nuxt cookie的设置就像beolw:

%7B%22city%22%3A%22%22%2C%22display_city%22%3A%22display_city%22%2C%22id%22%3A%22id%22%2C%22pincode%22%3A%22%22 %2C%22locality%22%3A%22%22%2C%22subCityId%22%3A%22%22%2C%22subCityName%22%3A%22%22%2%2C%22name%22%3A%22vandan%22%2C %22mobile%22%3A%228423847324%22%7D

意味着大括号和冒号在nuxt js中通过uriencoded方案自动进行了编码。因此,由于这个原因,由于cookie设置为不同的值,因此我在php上的默认功能无法正常工作。我希望我的js完全像php一样设置cookie。

这是我用来设置cookie的js代码:

this.$cookies.set(
  'gd_uc',
  JSON.stringify({
    city: cityData.city,
    display_city: cityData.display_city,
    id: cityData.id,
    pincode: '',
    locality: '',
    subCityId: '',
    subCityName: '',
    name: cityData.name,
    mobile: cityData.number
  })
cookies yii2 nuxt.js
1个回答
0
投票

[我知道,您遇到的问题是您使用的插件使用encodeURIComponent作为编码的默认函数,因此您将必须使用自己的函数来获取所需的输出格式(以匹配PHP所做的工作)

值得庆幸的是,您可以将自己的编码函数作为set函数的选项的一部分进行传递。这是set函数的第三个参数:

this.$cookies.set( 'gd_uc', data, { encode: function(){...}}

我要做的是这样的:

this.$cookies.set(
  'gd_uc',
  JSON.stringify({
    city: cityData.city,
    display_city: cityData.display_city,
    id: cityData.id,
    pincode: '',
    locality: '',
    subCityId: '',
    subCityName: '',
    name: cityData.name,
    mobile: cityData.number
  }),
  encode: function(value){
    // 1. remove the { and } characters
    // 2. pass the resulting string to encodeURIComponent
    // 3. Add { and } to the beginning and the end of your string
    return `{${encodeURIComponent(value.replace(/[\{\}]/g,''))}}`;
  }
)

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.