I'm having an issue when following this tutorial https://devcenter.heroku.com/articles/s3-upload-node
I've setup the code here https://desolate-island-40106.herokuapp.com/account and get the following error:
XMLHttpRequest cannot load
https://s3.amazonaws.com/nns.app.images/Nom%20Nom%20Snap.png?AWSAccessKeyId…=1466571088&Signature=9zyWWJrY5oQQtunDbZ1oRtVrJSo%3D&x-amz-acl=public-read.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'https://desolate-island-40106.herokuapp.com' is
therefore not allowed access.
The app gets a signed request successfully but the error occurs in the below where xhr.status = 0:
function uploadFile(file, signedRequest, url){
const xhr = new XMLHttpRequest();
xhr.open('PUT', signedRequest);
xhr.onreadystatechange = () => {
if(xhr.readyState === 4){
if(xhr.status === 200){
document.getElementById('preview').src = url;
document.getElementById('avatar-url').value = url;
}
else{
alert('Could not upload file.');
}
}
};
xhr.send(file);
}
Anyone have any ideas?
Related
I am writing a handler for an intent to generate a PDF. This API accepts a POST request with the JSON data and returns a link to the generated PDF. The intent triggers this code but the answer is not added to the agent. Is it possible that the request is not forwarded to the destination? The API seems to not get any requests. Any idea how to solve this?
function fillDocument(agent) {
const name = agent.parameters.name;
const address = agent.parameters.newaddress;
const doctype = agent.parameters.doctype;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var url = "https://us1.pdfgeneratorapi.com/api/v3/templates/36628/output?format=pdf&output=url";
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Auth-Key", "...");
xhr.setRequestHeader("X-Auth-Secret", "...");
xhr.setRequestHeader("X-Auth-Workspace", "...");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
agent.add(json.response);
}
};
var data = JSON.stringify({...});
xhr.send(data);
}
EDIT: I proceeded to set up a billing account in GCP, now the call works, but it is async. If I change it to syn by doing this:
xhr.open("POST", url, false);
I get the following error:
EROFS: read-only file system, open '.node-xmlhttprequest-sync-2'
I need it to be async as the response my bot is supposed to send depends on the response from the API. Any ideas on how to go around this?
If you are doing async calls, your handler function needs to return a Promise. Otherwise the handler dispatcher doesn't know there is an async call and will end immediately after the function returns.
The easiest way to use promises with network calls is to use a package such as request-promise-native. Using this, your code might look something like:
var options = {
uri: url,
method: 'POST',
json: true,
headers: { ... }
};
return rp(options)
.then( body => {
var val = body.someParameter;
var msg = `The value is ${val}`;
agent.add( msg );
});
If you really wanted to keep using xhr, you need to wrap it in a Promise. Possibly something like
return new Promise( (resolve,reject) => {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// ... other XMLHttpRequest setup here
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
agent.add(json.response);
resolve();
}
};
});
I am running the following script in a Windows command prompt with node myscript.js. The script requests a web application which is using Windows Authentication. I expect to receive status code 200. But the script returns a 401 Unauthenticated.
let request = require('request');
console.log(process.env.USERDOMAIN);
console.log(process.env.USERNAME);
request('http://internalurl',
function (error, response, body){
if (!error && response.statusCode == 200){
console.log('request successful!');
var input = JSON.parse(body);
}
console.log(response);
});
The process.env.USERNAME displays my current username which should have access to the web application. Because of this I am assuming that the script is running under the correct user account. What is the best practice to login into the web application?
It's normal to receive a 401 message when using Windows authentication - that's the first step in the Windows authentication process. The WWW-Authenticate header in the 401 response then tells you which authentication mechanisms are available (either NTLM or Negotiate).
The accepted answer to this question describes the process in more detail: https://stackoverflow.com/a/13960538/1202807
However, that answer doesn't provide a solution for a node client. But the last answer to that question does give an example of how to do it with node-libcurl:
var endpoint = urlString;
var url = require("url");
var endpointUrl = url.parse(endpoint);
var Curl = require( 'node-libcurl' ).Curl;
var curl = new Curl();
curl.setOpt( 'USERNAME', '' );
//curl.setOpt( 'VERBOSE', 1 );
curl.setOpt( 'URL', endpoint );
curl.setOpt( 'HTTPAUTH', Curl.auth.NEGOTIATE );
curl.setOpt( 'NOPROXY', endpointUrl.hostname );
curl.on( 'end', function( statusCode, body, headers ) {
if (statusCode === 200) {
console.log(body);
cb(null, { statusCode, body, headers } );
} else {
cb(new Error(), { statusCode, body, headers } );
}
this.close();
});
curl.on( 'error', curl.close.bind( curl ) );
curl.perform();
I've never done this in node myself though, so that's about all the help I can be.
I am trying to make a request to github's API. Here is my request:
var url = 'https://api.github.com/' + requestUrl + '/' + repo + '/';
request(url, function(err, res, body) {
if (!err && res.statusCode == 200) {
var link = "https://github.com/" + repo;
opener(link);
process.exit();
} else {
console.log(res.body);
console.log(err);
console.log('This ' + person + ' does not exist');
process.exit();
}
});
This is what I get for my response:
Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.
I have used the exact same code in the past, and it has worked. No errors are being thrown by request. Now I am confused with why I am getting a 403 (Forbidden)? Any solutions?
As explained in the URL given in the response, requests to GitHub's API now require a User-Agent header:
All API requests MUST include a valid User-Agent header. Requests with no User-Agent header will be rejected. We request that you use your GitHub username, or the name of your application, for the User-Agent header value. This allows us to contact you if there are problems.
The request documentation shows specifically how to add a User-Agent header to your request:
var request = require('request');
var options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
From C# and using HttpClient you can do this (tested on latest .Net Core 2.1):
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");//Set the User Agent to "request"
using (HttpResponseMessage response = client.GetAsync(endPoint).Result)
{
response.EnsureSuccessStatusCode();
responseBody = await response.Content.ReadAsByteArrayAsync();
}
}
Thanks
If Github API is responding with status Code : 403, It simply mean
that your API fetching limit has been exceeded please wait for 1 min and again fetch then you will get your data,
ANGULAR
I had the same issue where I got 403 rate limit exceeded. I tried setting up the Authorization header using new HttpHeaders from angular/common but the header still failed.
The code that failed is:
getUser(username: string): Observable<any> {
this.headers.set('Authorization', `token ${this.ACCESS_TOKEN}`);
const endpoint = `https://api.github.com/users/${username}`;
return this.http.get(endpoint, {
headers: this.headers
}).pipe(response => {
return response
});
}
The code that worked:
getUser(username: string): Observable<any> {
const endpoint = `https://api.github.com/users/${username}`;
return this.http.get(endpoint, {
headers: {
Authorization: `token ${this.ACCESS_TOKEN}`,
}
}).pipe(response => {
return response
});
}
In this case, I directly set the header in the request headers segment.
This answers the question and as a bonus shows you how to check if there is a new release
You need to add a User-agent to the Request
request.UserAgent = "YourRepoName";
internal class Tag
{
[JsonProperty("tag_name")]
public string TagName { get; set; }
}
/// <summary>
/// Use the Github API to Check for Updates
/// </summary>
/// <returns></returns>
public static Task<string> CheckUpTodate()
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.github.com/repos/HypsyNZ/BinanceTrader.NET/releases");
request.UserAgent = new Random(new Random().Next()).ToString();
var response = request.GetResponse();
if (response != null)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string readerOutput = reader.ReadToEnd();
List<Tag>? deserializedString = JsonConvert.DeserializeObject<List<Tag>>(readerOutput);
if (deserializedString != null)
{
if (deserializedString.Count > 0)
{
Tag tagOnFirstRelease = deserializedString.FirstOrDefault();
if ("v" + ObservableObject.Version == tagOnFirstRelease.TagName)
{
return Task.FromResult("Up To Date");
}
else
{
return Task.FromResult("Update Available: " + tagOnFirstRelease.TagName);
}
}
}
}
}
catch (Exception ex)
{
// Error
}
return Task.FromResult("Unknown");
}
I'm making a simple request to an rss feed:
var request = require('request');
var req = request('http://www.govexec.com/rss/contracting/');
req.on('error', function (error) {
console.log('error:',arguments);
});
req.on('response', function (res) {
var stream = this;
if (res.statusCode != 200) return this.emit('error', new Error('Bad status code'),res.statusCode);
});
output is error: { '0': [Error: Bad status code], '1': 500 }
However, if I hit the url from the browser, or do a simple curl request, I get the correct response
curl 'http://www.govexec.com/rss/contracting/'
It's not a programming problem, per say.
Most websites do expect you to send the header user-agent with your request. It seems to be this way with the website you have provided too.
Fixing this is trivial, since you can use include the user-agent like so:
var req = request({
url:'http://www.govexec.com/rss/contracting/',
headers: {
'User-Agent': 'request'
}
});
If I run this Code:
function sendRequest() {
var req = new XMLHttpRequest();
req.open("GET", "http://www.google.com/search?XXXX", true);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
alert( req.responseText );
}
}
};
req.send();
}
I get this error:
XMLHttpRequest cannot load http://www.google.com/search?XXXX. Origin chrome-extension://loifkhcbcjakjhcmecadcbdgfldfjfce is not allowed by Access-Control-Allow-Origin.
why??
In manifest file I have:
"permissions": [
"<all_urls>"
]
Demi
That will work for a packaged Chrome app, but not a hosted one.