返回HTML响应并添加Cookie-Cloudflare Worker



我试图返回一个"Set Cookie"的响应标头,同时通过编辑CSS返回一个新的HTML响应。换句话说,我正在寻找一种在一个实例中执行这两个操作的方法(或者将我的两个IF语句合并为一个(:

const country = request.cf.country
let cookies = request.headers.get('Cookie') || ""
const url = new URL(request.url)
let response = await fetch(request);
response = new Response(response.body, response);
if (country != 'US' && country !='CA') {
response.headers.set('Set-Cookie', "new-int-pricing-mode=on;max-age=604800;Path=/");
return response;
}

if (country != 'US' && country !='CA') 
{const response = await fetch(request)
var html = await response.text()

// Inject scripts
const customScripts = '<style type="text/css">STYLING HERE</style></body>'
html = html.replace( /</body>/ , customScripts)

// return modified response
return new Response(html, response)
}

因为我正在返回一个新的响应,并且只返回一个"响应";响应";在另一个——到目前为止,我所有的";合并";技术正在失败。这可能吗?

我已经通过使用cookie成功地实现了99%的合并。但在第一页加载时,样式将不会生效(由于需要应用cookie(

if ((country != 'US' && country !='CA') && !(cookies.includes("pricing-mode=on"))) {
response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");
return response;
}
else if ((country != 'US' && country !='CA') && (cookies.includes("pricing-mode=on"))) {
const response = await fetch(request)
var html = await response.text()

// Inject scripts
const customScripts = '<style type="text/css">STYLE HERE</style></body>'
html = html.replace( /</body>/ , customScripts)

// return modified response
return new Response(html, response)
}

您可以创建一个新的响应对象。https://developers.cloudflare.com/workers/examples/modify-response/

const originalResponse = await fetch(request);
// Change status and statusText, but preserve body and headers
let response = new Response(originalResponse.body, {
status: 500,
statusText: 'some message',
headers: originalResponse.headers,
});

您可以使用向该响应添加标头response.headers.set('Set-Cookie', "pricing-mode=on;max-age=604800;Path=/");

最新更新