问题
I do the following:
var headers = new Headers();
headers.append("bunny", "test");
headers.append("rabbit", "jump");
fetch("blahurl.com/someservice", {headers:headers})
On the firebase end:
export const listener = functions.https.onRequest(async (req, res) => {
for (let entry of req.rawHeaders) {
console.log(entry); // here I see a 'bunny,rabbit' get printed somewhere
}
//However this yields undefined:
req.headers.bunny
Not sure how to get the header values, I just have the headers...
回答1:
You should check Parsing HTTP requests.
You could simply get the request header by this method:
req.get('bunny');
req.get('rabbit');
回答2:
Looks like the issue was with cors, so moving the body of the function into it worked, like so:
const cors = require('cors')({ origin: true });
export const listener = functions.https.onRequest(async (req, res) => {
cors(req, res, () => {
And then the cookies started appearing correctly...
I'm not entirely sure why though, this isn't a response thing it's just a request.
回答3:
I found this answer while searching for "firebase request header is undefined".
Problem
I have written a firebase function (using Node JS) that I am posting to. The post included a header entitled "user_token". In my code, I retrieved the header value like this:
const userToken = request.header("user_token");
I tested this code on my local machine by using the Firebase CLI server (firebase serve) and it worked fine.
However, once I deployed this code (firebase deploy) to my Firebase account, I ran into a problem. Posting the exact same header key/value to my Firbase URL, I was getting errors because the userToken value was undefined.
Solution
Ultimately, changing my code to the following solved my problem:
const userToken = request.get("x-user-token");
@Ben's answer helped point me in the right direction. Initially, I simply changed my code to:
const userToken = request.get("user_token");
Unfortunately, I still ended up with an undefined userToken value. Looking over the Parsing HTTP requests documentation, I noticed that their sample header value key began with "x-". Updating my header value key from "user_token" to "x-user-token" did the trick.
回答4:
If someone still has the same problem this is the solution for typscript:
To Slove the CORS Problem first:
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const getmBucksShop = functions.https.onRequest((request, response) => {
corsHandler(request, response, () => {
//Access Header Values here
//Your Code Here
});
});
Does not work:
console.error(request.headers.authorization);
Does Work:
console.error(request.headers['authorization']);
console.error(request.get("authorization"));
Using this dependencies:
"dependencies": {
"cookie-parser": "^1.4.3",
"cors": "^2.8.5",
"express": "^4.16.4",
"firebase-admin": "~6.0.0",
"firebase-functions": "^2.1.0"
},
来源:https://stackoverflow.com/questions/47851528/cant-see-value-of-request-headers-in-firebase