How can I send a cookie via node-fetch - javascript

I recently started to work with the roblox api, It's been going good so far but I can't login. I tried to set the cookie by doing apiCall.headers.set-cookie = cookie, But that doesn't seem to work. How can I solve this issue?
Would I have to get set-cookie then edit it? i.g
const cookieSet = await apiCall.headers.get("set-cookie")
cookieSet = cookie
If I made it difficult to understand, I'll try to make it more clear
How would I post a cookie to a roblox API?
My code:
if (!cookie.startsWith("_|WARNING:")) {
throw new Error("Make sure your token is correct")
}
const cookies = {
headers: {
cookie: cookie
}
}
await fetch("https://www.roblox.com", cookies)
const thing = await fetch('https://api.roblox.com/currency/balance', cookies).then(res => res.json())
console.log(thing)
Thing outputs : { errors: [ { code: 403, message: 'Forbidden' } ] }

Well turns out I had to access the cookie from the Header. I did so by doing
const apiCall = await html.func("api.roblox.com/currency/balance", {
headers: {
cookie: `.ROBLOSECURITY=${cookie}`
}
})
Thanks for those who tried to help me!

Related

How can I access the token which is saved in the header using angular

I am sending the 'auth-token' which is generated with JWT to the frontend which is built in angular. The backend is built in nodejs. when I try to access the auth-token variable from the frontend it is saying syntax error. How can access this header token in my angular code?
Frontend Request in the component
onSubmit(){
if(!this.signinForm.valid){
return;
}
const userDetails: SigninAccount = {
email: this.signinForm.controls.email.value,
password: this.signinForm.controls.password.value
}
this.loginservice.loginUser(userDetails).subscribe(
data => { console.log(data);
this.router.navigate(['/'])
},
error => { console.log(error.error)}
)
}
Frontend service and the headeroptions
const loginhttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
}
loginUser(user: SigninAccount): Observable<SigninAccount> {
const makeReqURL = `${this.apiURL}/login`;
const loginUser = this.http.post<SignupAccount>(makeReqURL, user, httpOptions)
return loginUser;
}
Backend response
const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
res.header('auth-token', userToken).send(userToken)
Screenshot of the image in the browser and the syntax error message which is given because of the console.log(data).
the "text" has the JWT token too which is the same as the "auth-token" but don't know how to access it in the code and I don't know what is the syntax error either.
Please help. Thank you very much in advance.
There must be some syntax issue in backend code that's why you getting the error. Use some linter like EsLint which can help detecting the error.
How to access the authToken?
Here is your new backend code.
don't set token in header instead send as a json.
const userToken = jwt.sign({ _id: user._id }, process.env.TOKEN);
res.json({token: userToken});
The frontend code is correct you gonna get your token in console.
this.loginservice.loginUser(userDetails).subscribe(
data => {
console.log(data);
const token = data.token;
//Save to localStorage
localStorage.setItem('token',token);
this.router.navigate(['/']);
},
error => { console.log(error.error)}

Authenticated requests after sign in with React Query and NextAuth

I'm having troubled sending an authenticated request to my API immediately after signing in to my Nextjs app using NextAuth. The request that is sent after signing in returns data for and unauthenticated user.
I believe the issue is that React Query is using a previous version of the query function with an undefined jwt (which means its unauthenticated). It makes sense because the query key is not changing so React Query does not think it's a new query, but, I was under the impression that signing in would cause loading to be set to true temporarily then back to false, which would cause React Query to send a fresh request.
I've tried invalidating all the queries in the app using queryClient, but that did not work. I've also used React Query Devtools to invalidate this specific query after signing in but it still returns the unauthenticated request. Only after refreshing the page does it actually send the authenticated request.
// useGetHome.js
const useGetHome = () => {
const [session, loading] = useSession();
console.log(`session?.jwt: ${session?.jwt}`);
return useQuery(
'home',
() => fetcher(`/home`, session?.jwt),
{
enabled: !loading,
},
);
}
// fetcher
const fetcher = (url, token) => {
console.log(`token: ${token}`);
let opts = {};
if (token) {
opts = {
headers: {
Authorization: `Bearer ${token}`,
},
};
}
const res = await fetch(`${process.env.NEXT_PUBLIC_BACKEND_URL}${url}`, opts);
if (!res.ok) {
const error = await res.json();
throw new Error(error.message);
}
return res.json();
}
// Home.js
const Home = () => {
const { data: home_data, isLoading, error } = useGetHome();
...
return(
...
)
}
Attached is the console immediately after signing in. You can see the the session object contains the jwt after signing in, but in the fetcher function it is undefined.
console after signing in
Any help here is appreciated. Is there a better way to handle authenticated requests using React Query and NextAuth? Thank you!
I have tried a similar situation here and struggled the same thing but the enabled property worked fine for me and it is good to go right now.
https://github.com/maxtsh/music
Just check my repo to see how it works, that might help.

cross origin for amazon lambda function from localhost in gatsby site

I have the following code which works when I run it as a local serverless function with netlify dev, but I need it to run cross origin from a dev server to the hosted server function. I put the function in a aws lambda function but I am getting a cross origin blocked error on my https:dev.website.com, I thought I have the correct headers in the return object so not sure why I am getting a cross origin error.
Any help would be great
const sanityClient = require("#sanity/client");
const client = sanityClient({
projectId: "random-id",
dataset: "production",
useCdn: true,
});
exports.lambdaHandler = async (event, context) => {
var body = JSON.parse(event.body);
//console.log(body.price_id)
try {
const checkPriceId = async (test) => {
const query = `*[_type == "products" && price_id == "${body.price_id}"]`;
const documents = await client.fetch(query, {}); // this could throw
return documents.map((document) => document.sold);
};
var ok = checkPriceId().then((test) => {
return new Promise(function (resolve, reject) {
//console.log(test) // this will log the return value from line 7
console.log(test);
resolve(test);
});
});
var bools = await ok;
// prettier-ignore
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods':'GET, POST, OPTION',
},
body: JSON.stringify({
sold: bools,
}),
};
} catch (err) {
return { statusCode: 500, body: err.toString() };
}
};
This is my request to the function if that helps
var fetchUrl = https://random.executue-api.aws.com/prod/sold //not exact
var fetchData = async function () {
const response = await fetch(fetchUrl, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
price_id: final,
}),
})
.then(res => {
return res.json()
})
.catch(error => console.log(error))
return response
}
Update:
I tried adding cors the way suggested in the answer below, but it failed seen below so I tried manually adding the method response seen after.
I still get a cross domain error. And I have changed the domain so it is now https as well. Really stuck here.
I was looking into this more, and it seems like before it does the actual post it does a cors check at the options method, so I added in the same access control headers, and deployed but did not work. Don't quite get this.
Your headers look ok to me. (note: If you mix HTTP and HTTPS you are most likely to get a mixed content error in the client). If it is ONLY a CORS issue that you are seeing in the console in the web browser, then you might not have configured the API Gateway correctly in AWS.
In AWS, go to API Gateway and you should see something like the below:
Make sure that you enable CORS and then redeploy.
UPDATE:
Just looking at a previous implementation of a lambda function I setup with AWS. The headers I declared were as follows:
headers: {
"Content-Type" : "application/json",
"Access-Control-Allow-Origin" : "*",
"Allow" : "GET, OPTIONS, POST",
"Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
"Access-Control-Allow-Headers" : "*",
"Access-Control-Allow-Credentials" : true
}
Your headers look OK to me though. However, when you created the method in the API Gateway, did you select Use Proxy Lambda Integration? (see screenshot).
Your client side fetch request looks ok. For reference mine was:
const url = 'your url';
const options = {
method: 'POST',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
};
fetch(url, options).then(res => res.json());
Unrelated to this issue, but its not advisable to mix Async/Await with .then promise chaining. But this isn't the issue you are having. Just something to note.
Check the values from your Integration Response / try setting them manually for both OPTIONS and POST (and if that works, make sure you are passing through the response correctly from the lambda).
Your POST action should only require the Access-Control-Allow-Origin header. The other two (Access-Control-Allow-Methods, Access-Control-Allow-Headers) belong in the OPTION action. See this writeup, and note the full example exchange for a preflighted request (in grey): https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests

How to make a fetch request with custom herokuapp proxy?

I'm trying to make a fetch request with custom herokuapp proxy to an API, but when I do that it gives an error. Error says "There is no Target-Endpoint header in the request". Here is my code.
var userTargetUrl = `http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=${steamApiKey}&vanityurl=${url}`
const response = await fetch(proxyUrl + userTargetUrl, {
headers: {
'Target-Endpoint': 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?'
}
})
const data = await response.json()
url = data['response']['steamid']
I'm following their instructions, but I couldn't figure it how to do it.
I won't pretend to be entirely sure, but maybe you can try
const response = await fetch(proxyUrl, {
headers: {
"Target-Endpoint": userTargetUrl
}
});

Get Steam Community Market price history with node.js

I'm having trouble getting the price history of an item from Steam. By looking at other questions I've managed to learn a nifty way to construct a link which indeed gives me the price history of an item, my problem is that you have to be logged in to Steam to aquire this data. How do I view this data as if I'm logged in through an http-request? I've read other threads where they talked about browser sessions and how someone in my situation should set cookies of ones session-id but I haven't managed to get it to work in node. The status code I'm getting is 400.
This is my code:
const https = require('https');
const options = {
host: 'steamcommunity.com',
path: '/market/pricehistory/?country=SE&currency=3&appid=730&market_hash_name=CS20%20Case',
method: 'GET',
headers: {
'Cookie': `steamLoginSecure=THE SESSION ID I GOT FROM WRITING
"document.cookie" IN THE DEV CONSOLE`
}
}
const req = https.request(options, res => {
console.log(res.statusCode);
console.log(res.headers);
let body = '';
res.on('data', data => {
body += data;
});
res.on('end', () => console.log(body));
}).on('error', error => console.log(error));
req.end();
I'm not sure if there's anything wrong in my code or how to go about to solve this issue I'm having. I really appreciate any help I can get.
It seems like Steam has removed the 'steamLogin' cookie, thus explaining why so many people this past year have been encountering issues when using it in their code. Instead, you want to use the 'steamLoginSecure' cookie.
First you need be logged in to https://steamcommunity.com. Second you want to find the 'steamLoginSecure' cookie and copy what it contains. For chrome that would be:
Settings > Advanced > Privacy and security > Site Settings > Cookies and site data > See all cookies and site data > steamcommunity.com > steamLoginSecure
Now copy the content of 'steamLoginSecure' and have it as a cookie in your headers.
This is the final code I ended up with:
const https = require('https');
const options = {
host: 'steamcommunity.com',
path: '/market/pricehistory/?country=SE&currency=3&appid=730&market_hash_name=CS20%20Case',
method: 'GET',
headers: {
'Cookie': 'steamLoginSecure=THE CONTENT OF "steamLoginSecure" HERE'
}
}
const req = https.request(options, res => {
console.log(res.statusCode);
console.log(res.headers);
let body = '';
res.on('data', data => {
body += data;
});
res.on('end', () => console.log(body));
}).on('error', error => console.log(error));
req.end();

Categories

Resources