I'm trying to get data from API, I get it with Node & Postman, but I can't make it work on the browser.
I get 403 Forbidden (anonymous).
Is it my problem or maybe something that's supposed to be enabled in the server?
var urlAPI = "http://example.com/api/v1/";
var uname = 'username';
var pass = 'password';
var headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(uname + ':' + pass));
fetch(urlAPI, {
mode: 'no-cors',
credentials: 'include',
headers: headers
})
.then(function () {
console.log("ok");
}).catch(function (err) {
console.log("error: " + err);
});
Related
I'm trying to create an app with the Spotify API, but can't seem to get it to work. The error I'm getting is that 'request' is undefined and I've replaced it with JQuery too and that doesn't work either. Can anyone tell me why I might be getting that error and how to fix it? Should I be running it inside node.js in cmd?
var client_id = '?';
var client_secret = '?';
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'client_credentials'
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var token = body.access_token;
}
else {
console.log(JSON.stringify(error))
}
});
The spotify documentation is out of date, as request is deprecated, and should no longer be used.
Instead, you can make a request with built-in Node.js libraries, as mentioned in the documentation.
It should be run with node.js, i.e. node <filename>
const https = require('https')
const client_id = 'CLIENT_ID'
const client_secret = 'CLIENT_SECRET'
const reqBody = JSON.stringify({
grant_type: 'client_credentials'
})
const authOptions = {
hostname: 'accounts.spotify.com',
port: 443,
path: '/api/token',
method: 'POST',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/json',
'Content-Length': reqBody.length
}
}
const req = https.request(authOptions, res => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
req.write(reqBody);
req.end();
I am using the Spotify Web API to get my access token. It is working perfectly.
In my frontend application, I would like to use axios to get the access token.
How can I do that?
Because my axios.get method is not working.
Here I am getting the access token:
app.get('/callback', function(req, res) {
your application requests refresh and access tokens after checking the state parameter
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
console.log('reqcookie', req.cookie)
if (state === null || state !== storedState) {
res.redirect('/#' +
querystring.stringify({
error: 'state_mismatch'
})
);
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':'
+
client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
console.log('accestoken ',access_token)
console.log('body', body)
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token
},
json: true
};
Use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log('hi')
console.log(body)
});
...not important code
console.log('Listening on 8888');
app.listen(8888);
That's how I use axios in my frontend application to get the data and later the access token.
But it is currently not working
axios({
method: 'get',
url: 'http://localhost:8000/callback'
}).then(data => console.log(data))
.catch(err => console.log(err))
I am calling below url with get https request using Node.js, here i need to send the session with cookie, since i know the vallue of cookie.
var URL = require('url-parse');
var appurl = "https://test.somedomain.com"
var https = require('https');
var url = new URL(appurl);
var options = {
host: url.host,
url: appurl,
path: url.pathname + url.query,
method: 'GET',
headers: {
"Set-Cookie": "cookiValue1=abcdesg"
}
};
var req = https.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// console.log(res.headers.)
// res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ', chunk);
});
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.write('data\n');
req.write('data\n');
req.end();
The header should be Cookie instead of Set-Cookie
Set-Cookie is used by the server to set a cookie on clients. Header Cookie is used to send a cookie to server by client.
So nodejs server it's not a browser which have window and document
try to send the same request in js client side not nodejs
You can set cookie only here
see POINTERs in the bottom
var URL = require('url-parse');
var https = require('https');
var appurl = "https://stackoverflow.com/"
var url = new URL(appurl);
var options = {
host: url.host,
url: appurl,
path: url.pathname + url.query,
method: 'GET',
headers: {
"Cookie": "1111111111=abcdesg", // POINTER its unfortunately useless
"Set-Cookie": "11111111=abcdesg" // POINTER its unfortunately useless
}
};
var req = https.request(options, function (res) {
console.log('before HEADERS: ' + JSON.stringify(res.headers));
res.headers.cookiValue1 = 'abcdesg'; // POINTER
console.log('after HEADERS: ' + JSON.stringify(res.headers));
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.write('data\n');
req.write('data\n');
req.end();
I am trying to use the Bing Search API to return a JSON string. I first tried using the following url as per Azure's explore website (https://datamarket.azure.com/dataset/explore/5BA839F1-12CE-4CCE-BF57-A49D98D29A44):
'https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27NGI%20SPA%27&Market=%27en-US%27'
After, I found a SO thread Using the new Bing API (nodejs) which suggested I use a url of the form:
https://user:<YourDefaultAccountKey>#api.datamarket.azure.com/Bing/SearchWeb/Web?Query=%27leo%20fender%27&Market=%27en-US%27&$top=50&$format=JSON
Both of these return status 401 (Authentication Failure):
STATUS: 401
HEADERS: {"content-type":"application/json; charset=utf-8","server":"Microsoft-IIS/8.0","jsonerror":"true","x-powered-by":"ASP.NET","access-control-allow-origin":"*","access-control-allow-credentials":"false","access-control-allow-headers":"Authorization, DataServiceVersion, MaxDataServiceVersion","access-control-expose-headers":"DataServiceVersion, MaxDataServiceVersion","access-control-allow-methods":"GET, POST, OPTIONS","access-control-max-age":"604800","date":"Wed, 02 Jul 2014 17:23:29 GMT","content-length":"91"}
BODY: {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
I have also tried other various combinations of URLs to no avail. My code is below:
var url = require('url');
var http = require('http');
var serviceRootURL = 'https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27web%27&Query=%27NGI%20SPA%27&Market=%27en-US%27'
var params = 'hi';
var dataURL = url.parse(serviceRootURL);
var post_options = {
hostname: dataURL.hostname,
port: dataURL.port || 80,
path: dataURL.path,
method: 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Content-Length': params.length
}
};
var req = http.request(post_options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Any idea why I am getting an authentication failure?
You can use this module that encapsulates the requests, so you can use it
like:
var Bing = require('node-bing-api')({ accKey: "your-account-key" });
Bing.web("leo fender", function(error, res, body){
console.log(body);
},
{
top: 50,
market: 'en-US'
});
It works with the Azure version. You only have to replace your account key.
Got it working with request...weird
var request = require('request');
var _ = require('underscore');
var searchURL = 'https://user:<TIPE YOUR KEE HEER>#api.datamarket.azure.com/Bing/SearchWeb/v1/Web?Query=%27xbox%27&$top=10&$format=JSON';
var http = request( searchURL, function(err, resp, body)
{
if ( err )
{
throw err;
}
var a = JSON.parse(body);
console.log(a.d.results);
});
you can use jsearch module. install ;
npm install jsearch
usage;
js.bing('queryStringYouWant',10,function(response){
console.log(response) // for Bing results
})
I'm trying to run this code but getting this error:
Request forbidden by administrative rules, make sure your request has a User-Agent header
var https = require("https");
var username = 'jquery';
var options = {
host: 'api.github.com',
path: '/users/' + username + '/repos',
method: 'GET'
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){
body += chunk.toString('utf8');
});
response.on("end", function(){
console.log("Body: ", body);
});
});
request.end();
Your options object does not have the headers option, describing the user-agent. Try this:
var options = {
host: 'api.github.com',
path: '/users/' + username + '/repos',
method: 'GET',
headers: {'user-agent': 'node.js'}
};