API call working in chrome but not postman - api

I am trying to call this API endpoint https://core-api.prod.blur.io/v1/collections/doodles-official/tokens?filters=%7B%22traits%22%3A%5B%5D%2C%22hasAsks%22%3Atrue%7D in a backed environment.
It work in google chrome, but when I try to make a request through node.js or postman, I get a status 403 'Forbidden'.
I added all the Chrome request headers in my options object but it still doesn't work.
const getListings = async function() {
const options = {
/* Add whatever Chrome display in the Network settings tab of the request */
};
const res = await fetch(`https://core-api.prod.blur.io/v1/collections/mutant-ape-yacht-club/tokens?filters=%7B%22traits%22%3A%5B%5D%2C%22hasAsks%22%3Atrue%7D`, options)
.then(res => {
console.log(res);
return res.json();
})
.catch(err => console.log(err));
return res;
}
I simply would like to use this URL that works in the browser in my backend application. I don't understand how this can work in my browser and not in a backed environment.

Related

refetch or poll an external api with fetch in svelte

New to Svelte and am running into some issues.
Currently doing the following in +page.server.js
I would like to poll this API every couple hundred milliseconds, I am unsure how to do that. I have tried using set Interval here to no avail.
export async function load({params}) {
const response = await fetch(
`http://localhost:9595/api/v1/chrysalis/example?uid=${params.uid}`
)
const site = await response.json()
const siteData = site[0]
console.log(siteData)
return {
uid: params.uid,
partitions: siteData.partitions,
zones: siteData.zones,
zTypes: siteData.zTypes,
zStates: siteData.zStates,
zNames: siteData.zNames
}
}
For example, I've built this in next.Js using SWR with refreshInterval: 1.
const {data, error, isLoading} = useSWR(
'http://localhost:9595/api/v1/chrysalis/example',
(url) => {
const searchParams = new URLSearchParams();
searchParams.append("uid", body.uid)
const newUrl = `${url}?${searchParams.toString()}`
const options = {
method: 'GET',
headers: {'Content-Type': 'application/json'},
}
return fetch(newUrl, options).then(res => res.json())
},
{
refreshInterval: 1
}
);
I have also tried to do the following onMount of the +page.svelte but when trying to hit the API from the client I get CORS error.( ran into this before if +page.js was not +page.server.js
let x;
onMount(async () => {
setInterval(async () => {
const response = await fetch(
`http://localhost:9595/api/v1/chrysalis/example?uid=${data.uid}`
)
const site = await response.json()
x = site[0]
console.log(x)
}, 3000)
})
The CORS error results because +page.svelte/+page.js are run in the browser. So you need to proxy the call through a service that allows being called from the browser. (Or relax the CORS restrictions on http://localhost:9595)
You can use SvelteKit itself to proxy the call by creating an internal endpoint. So:
The internal endpoint simply fetches http://localhost:9595/... and returns the results. (You can just forward the response object from fetch())
+page.svelte calls that internal endpoint from setInterval().

Trying to set a cookie established on a web session as a header back to API

I am trying to login via the webfront end and trying to intercept a cookie and then using that in the subsequent API request. I am having trouble getting the cookie back into the GET request. Code posted below.
import https from 'https';
import { bitbucketUser } from "../userRole.js"
import { ClientFunction } from 'testcafe';
fixture `Request/Response API`
// .page `https://myurl.company.com/login`
.beforeEach(async t => {
await t.useRole(bitbucketUser)
});
test('test', async t => {
const getCookie = ClientFunction(() => {
return document.cookie;
});
var mycookie = await getCookie()
const setCookie = ClientFunction(mycookie => {
document.cookie = mycookie;
});
var validatecookie = await getCookie()
console.log(validatecookie)
const executeRequest = () => {
return new Promise(resolve => {
const options = {
hostname: 'myurl.company.com',
path: '/v1/api/policy',
method: 'GET',
headers: {
'accept': 'application/json;charset=UTF-8',
'content-type': 'application/json'
}
};
const req = https.request(options, res => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
console.log(body);
});
resolve();
});
req.on('error', e => {
console.error(e);
});
req.end();
});
};
await setCookie(mycookie)
await executeRequest();
});
I have tried several examples but am quite not able to figure what is it that I am missing.
When you call the setCookie method, you modify cookies in your browser using the ClientFunction.
However, when you call your executeRequest method, you run it on the server side using the nodejs library. When you set cookies on the client, this will not affect your request sent from the server side. You need to add cookie information directly to your options object as described in the following thread: How do I create a HTTP Client Request with a cookie?.
In TestCafe v1.20.0 and later, you can send HTTP requests in your tests using the t.request method. You can also use the withCredentials option to attach all cookies to a request.
Please also note that TestCafe also offers a cookie management API to set/get/delete cookies including HTTPOnly.

Vue axios doesnt change header

I am quite new to vue and I am trying to send a request to my api using axios.
I build an interceptor which seems to work (logging is happening)
export default function setup() {
console.log('Http interceptor starting...')
Axios.interceptors.request.use((request) => {
const token = store.getters.token;
if (token) {
request.headers.Authorization = `Bearer ${token}`;
}
console.log(request);
return request
}, (err) => {
return Promise.reject(err);
});
}
If I check the console I can see the request including the token. If I check my network tab in the browser i can see the same request without the token. If I check the console of my api the token is null. Any Ideas?
Edit: If I use postman with the same request and the same token it is working as it shuld

Difficulty registering callback url with IBM watson speech-to-text npm module

I'm trying to register a callback url for the IBM speechToText service, using express, and I keep getting a 400 response when I call speechToText.registerCallback.
I've already ensured that the url exists and is providing responses as expected via Postman. I also know that my SpeechToText service has correct credentials.
I'm not seeing the 'challenge_string' logged when I call the endpoint using registerCallback.
router.get('/callback', (req,res,next) => {
console.log(req.query.challenge_string);
return res.status(200);
});
router.post('/newStream', (req,res) => {
var speechToText = new SpeechToTextV1({
username: <my_username>,
password: <my_password>,
url: 'https://stream.watsonplatform.net/speech-to-text/api/'
});
const registerCallbackParams = {
callback_url: 'http://127.0.0.1:8080/callback',
user_secret: 'ThisIsMySecret',
};
speechToText.registerCallback(registerCallbackParams)
.then(registerStatus => {
console.log(JSON.stringify(registerStatus, null, 2));
})
.catch(err => {
console.log(registerCallbackParams);
console.log('error:', err);
});
}```
It seems like the hostname in your callback url is 127.0.0.1, that is not a public hostname, but the address of the loopback interface.

puppeteer hangs chromium on request.continue if header is modified on 302 response code

Chromium is getting hanged if header is modified using puppeteer
Puppeteer version:1.12.2
Platform / OS version: MAC / UBUNTU
'use strict';
const puppeteer = require('puppeteer');
(async () => {
try {
let browser = await puppeteer.launch({ headless: false });
let [page] = await browser.pages();
await page.setRequestInterception(true);
page.on('request', request => {
const headers = Object.assign({}, request.headers(), {
foo: 'bar'
});
request.continue({ headers });
});
await page.goto('http://google.com');
} catch (err) {
console.error(err);
}
})();
In my case, this was not relevant to setting headers.
When I enabled request interception with this line of code observing the same behavior:
await page.setRequestInterception(true);
If I comment out this line of code it is loading the page but the Chromium is complaining that the connection is insecure. In this case waitUntil option does not work within page.goto as option.
If I open a new tab in Chromium (the same window) and copy and paste the same url it is loading the page without any isues.