I have a ExternalServe (running on Localhost)
When I using Browser to request:
localhost:2013/ExternalServer/getfilebyname?filename=getStatus.json
Then browser downloaded getStatus.json to Download Folder.
In my NodeJS project, I want to download getStatus.json file and I made:
download.js
var http = require('http');
var fs = require('fs');
function getFile (){
var file = fs.createWriteStream("./../lib/user.json");
var req = http.get("http://localhost:2013/ExternalServer/getfilebyname?filename=getStatus.json", function(res) {
res.pipe(file);
});
}
getFile();
but when i run: node download.js the system return
<html><head><title>Apache Tomcat/8.0.0-RC1 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>This request requires HTTP authentication.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/8.0.0-RC1</h3></body></html>
How to fix it?
Best regard
You are getting the following error response:
This request requires HTTP authentication
Suggesting to add the Authorization information in header. Like:
var options = {
host: 'localhost',
port: 2013,
path: '/ExternalServer/getfilebyname?filename=getStatus.json',
headers: {
'Authorization': 'Basic ' + new Buffer(uname + ':' + pword).toString('base64')
}
};
request = http.get(options, function(res) {
res.pipe(file);
});
in case of proxy, you can use the following header instead:
Proxy-Authorization
The server wants a username and password, or requires another authorization mechanism, before it will let you access the file this way.
To see how to supply a user and password when making the request in node.js, look at How to use http.client in Node.js if there is basic authorization
How do we know this could be the problem?
Two interesting strings in the system return:
HTTP Status 401
and
This request requires HTTP authentication
From Wikipedia: List of HTTP Status Codes
401 Unauthorized Similar to 403 Forbidden, but specifically for use
when authentication is required and has failed or has not yet been
provided.[2] The response must include a WWW-Authenticate header field
containing a challenge applicable to the requested resource. See Basic
access authentication and Digest access authentication.
Another possibility is that a server could be set up to emit 401 instead of 403, but doesn't really accept any usernames or passwords.
Related
My browser is logging the following message in the devtools console:
No 'Access-Control-Allow-Origin' header is present on the requested resource.… The response had HTTP status code 503.
Background: I have two apps. One that is an Express Node application connected to a Mongo database. The other is a basic web application that makes POST requests to the Node application via the Fetch API to get data from Mongo.
Issue: Though I receive no CORS errors on my local machine, I am given the error below as soon as I deploy my basic web application to production. The web application that makes a POST request to the Node app and gives me this:
The POST request does seem to work and the data is saved into Mongo but this error is being marked as a "Critical Error" in Heroku and is quite annoying.
I realize that I could set the no-cors option in Fetch but I believe that it is required since I am making a request to a url that is different than the origin. Right?
Express Node App Code
In my app.js file I have set the correct headers to ensure that other applications can make requests from different origins
app.js
// Add headers so we can make API requests
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
routes/api/api.js
router.post('/users/:url/upload-csv/:csv_name', (req, res) => {
let csv_name = req.params.csv_name;
let csv_string = csv_name+req.body.csv_string;
User.findOne({url: req.params.url})
.then((user) => {
if (user.csv_files.length === 0) {
user.csv_files.push(csv_string);
} else {
let foundExistingCSV = false;
for (var i = 0; i < user.csv_files.length; i++) {
if (user.csv_files[i].includes(csv_name)) {
foundExistingCSV = true;
user.csv_files[i] = csv_string;
break;
}
}
if (!foundExistingCSV) user.csv_files.push(csv_string);
}
user.markModified('csv_files');
user.save();
res.status(204);
})
.catch((err) => {
console.log(err);
res.status(400);
});
});
Basic Web App Code
POST request I am making
utils.js
utils.exportToMongo = functions(table, name) {
var exportPlugin = table.getPlugin('exportFile');
var csv_string = exportPlugin.exportAsString('csv');
// Upload the CSV string and its name to Users DB
fetch(`${utils.fetchUserURL()}/upload-csv/${name}`, {
method: 'POST',
body: JSON.stringify({csv_string: csv_string}),
headers: new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
})
}).then((res) => {
return {};
}).catch((error) => {
console.log(error);
return {};
});
}
How can I remove the 503 error? Any insight would be greatly appreciated!
An HTTP 5xx error indicates some failure on the server side. Or it can even indicate the server just isn’t responding at all — e.g., a case might be, your backend tries to proxy a request to a server on another port, but the server is not even be up and listening on the expected port.
Similarly, a 4xx indicates some problem with the request prevented the server from handling it.
To confirm, you can try making the same request using curl, or Postman, or something, and see if you get a 2xx success response for the request, rather than a 5xx or 4xx.
Regardless, if you see a 5xx or 4xx error on the client side, some message should get logged on the server side to indicate what failed and why. So to identify what triggered the 5xx/4xx error, check server logs to find messages the server logged before it sent the error.
As far as CORS error messages go, it’s expected that in most cases for a 5xx or 4xx error, servers won’t add the Access-Control-Allow-Origin response header to the response; instead the server most likely will only send that header for 2xx and 3xx (redirect) responses.
So if you get the cause of an 5xx/4xx error solved such that you can get a success response, you may find your CORS config is already working fine and you’ve got nothing left to fix.
I had the same issue, the server doesn't support cross origin request. The API developer should change Access-Control-Allow-Origin to * (means from any origin).sometimes jsonp request will bypass, if its not working, google chrome provides plugins to change origin
plugin
When giving the following configuration its returns always WebHook responds with incorrect HTTP status. HTTP status is 405.
This is the webhook configuration:
var token= access_token;
var _eventFilters = [];
_eventFilters.push('/restapi/v1.0/account/~/extension/' + 232102004 + '/presence?detailedTelephonyState=true&aggregated=true')
rcsdk.platform().post('/subscription',
{
eventFilters: _eventFilters,
deliveryMode: {
"transportType": "WebHook",
"encryption": false,
"address": "https://demo.example.com/backend/country-list/web_hook/?auth_token="+token
}
})
.then(function(subscriptionResponse) {
console.log('Subscription Response: ', subscriptionResponse.json());
})
.catch(function(e) {
console.error(e);
});
This is my Django webhook url:
#list_route(methods=['get'], url_path='web_hook')
def create_web_hooks(self, request, **kwargs):
query_params = request.query_params.dict()
from django.http import HttpResponse
response = HttpResponse()
if 'auth_token' in query_params:
response['Validation-Token'] = query_params['auth_token']
response['status'] = 200
response.write('Hello World')
return response
Thanks in advance
In your webhook response, the content of response['Validation-Token'] needs to be the value present in the RingCentral create webhook HTTP request's Validation-Token header. The RingCentral OAuth 2.0 access token is not used in your webhook listener.
Your webhook example is in Python so here are some examples using both Django and Flask. You should check for the existence of the request header and, if present, set the value as the response header of the same name. The following shows how to set the header.
Django
In Django, request headers are available in HttpRequest.META which renames headers using it's specific algorithm. META is a dictionary so you can access the header in the following ways:
response['Validation-Token'] = request.META.get('HTTP_VALIDATION_TOKEN')
or
response['Validation-Token'] = request.META['HTTP_VALIDATION_TOKEN']
More information on Django handles this is available in the Request and response objects documentation for HttpRequest.META:
https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.META
This is the specific text on header renaming:
With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be mapped to the META key HTTP_X_BENDER.
Flask
Using Flask, you can access HTTP request headers using the flask.Request dictionary-like object the following ways:
response['Validation-Token'] = request.headers.get('Validation-Token')
or
response['Validation-Token'] = request.headers['Validation-Token']
This is discussed in the Flask Incoming Request Data documentation:
http://flask.pocoo.org/docs/0.12/api/#incoming-request-data
I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:
SubmitClick(){
//console.log('load Get User page'); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'deadpool#gmail.com',
first_name: 'Wade',
last_name: 'Wilson',
personal_phone: '(11) 91111-2222',
password: 'wolv3Rine'
})
})
//this.props.history.push('/get'); //change page layout and URL
}
and I get the following message on my browser:
OPTIONS http://localhost:4000/users/ 401 (Unauthorized)
Failed to load http://localhost:4000/users/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.
I'm using Google Chrome as my default browser.
My backend code is the following:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var basicAuth = require('express-basic-auth')
const app = express();
mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl'
}
}))
app.use(bodyParser.json());
app.use(function(err, req, res, next){
console.log(err);
//res.status(450).send({err: err.message})
});
app.use(require('./routes/api'));
app.listen(4000, function(){
console.log('Now listening for request at port 4000');
});
It may not be the same problem as the OP, but I was able to get basic auth protected fetches working just by adding a credentials mode...
fetch(
'http://example.com/api/endpoint',
{ credentials: "same-origin" }
)
See here: https://github.github.io/fetch/ under Request > Options
You're trying to access port 4000 (your API, or backend) from port 3000 (Your client). This violates the Same-origin policy, even though you're clearly running both the client and the API from the same machine.
To get around this the easiest way is to just fire up your client from the same port as your API (port 4000) this should allow your host to see that you're trying to access resources from the same domain/port which won't force a preflight request.
If that's not possible you'll have to configure CORS for your API, and this question doesn't give any details about the backend so I can't instruct you on how to do that at the moment.
And of course this approach obviously won't work if you're running two separate servers in production, but that's probably outside of the scope of this question.
I'm writing a website with AngularJS which communicates with an API on the server and provides some Info.
for Log in part I should send a http post request containing Email, Password and etc. It works fine on google Chrome and IE. I mean it sends the post request and gets a token. But in FireFox as I checked in Network, It sends an OPTION request and gets 200 but after that it does not send any post! hence my login would not disappear and I wont get any token.
what should I do for this situation?
App.config :
$httpProvider.defaults.withCredentials = true;
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8;';
$httpProvider.interceptors.push('httpRequestInterceptor');
Function in service which sends request :
this.loginEmail = function(f_email, f_pass, deviceModel, deviceOs) {
var data = $.param({
email: f_email,
password: f_pass,
device_model: deviceModel,
device_os: deviceOs
});
return $http({
method: "POST",
url: app.baseUrl + 'login_email/' + app.storeID + '/' + app.device_id,
data: data
}).success(function(response){
return response.status;
});
/*return $http.post(app.baseUrl + 'login_email/' + app.storeID + '/' + app.device_id, data).success(function(response){
return response.status;
}).error(function(response){
return response.status;
});*/
};
Server Credentials are true
CORS seems fine because I can do get request
EDIT:
Here's another thing that may be related to this problem:
in Chrome when I get logged in for get requests it sends the Token header
but for Post it doesn't
httpRequestInterceptor :
app.factory('httpRequestInterceptor', function ($cookieStore) {
return {
request: function (config) {
config.headers['Authorization'] = $cookieStore.get('Auth-Key');;
config.headers['Accept'] = 'application/json;odata=verbose';
return config;
}
};
});
The problem was caused by apache configurations.
before:
Access-Control-Allow-Headers: "authorization"
after:
Access-Control-Allow-Headers: "authorization, Content-type"
UPDATE :
On CORS requests if API requires some special headers like Auhtorization Token you must return all OPTIONS requests 200(ok!) if not the solution above would not work anyway.
Here's the code:
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit();
}
UPDATE 2 :
This OPTIONS problem occurs in REST framework for Django! For OPTIONS it evaluates the request by pursing whole api if there was a problem in it, you'll get error even though you have required permissions for sending request!
Example:
Suppose that there's a url like api/profile which needs an Authorization header for responsing profile details. You want to send the Cross Domain request for getting it. You set the right headers and click! You'll get unauthorized error! Why? Because the pre flighted request(OPTIONS) does not include any special header and browser sends it to server, server with REST framework evaluates the OPTIONS request by checking the whole request(get request with authorization header) but OPTIONS doesn't have any authorization header so this request is unauthorized!
DEVELOPMENTAL SOLUTION :
This problem can be solved either by Client-Side or Back-End. Front-End developer can install following plugin on chrome:
Allow-Control-Allow-Origin: *
Back-End developer can install a package which enables CORS on Django Framework.
I have two app with nodejs and angularjs.nodejs app has some code like this :
require('http').createServer(function(req, res) {
req.setEncoding('utf8');
var body = '';
var result = '';
req.on('data', function(data) {
// console.log("ONDATA");
//var _data = parseInput( data,req.url.toString());
var _data = parseInputForClient(data, req.url.toString());
switch (req.url.toString()) {
case "/cubes":
{
and this app host on http://localhost:4000.angularjs app host with node http-server module on localhost://www.localhost:3030.in one of my angularjs service i have some thing like this :
fetch:function(){
var data = '{somedata:"somedata"}';
return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
console.log(cubes);
});
}
but when this service send a request to server get this error:
XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access.
so i search the web and stackoverflow to find some topic and i find this and this . according to these topics i change the header of response in the server to something like this :
res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));
but this dose'nt work.I try with firefox,chrome and also check the request with Telerik Fiddler Web Debugger but the server still pending and i get the Access Control Allow Origin error.
You do POST request, which generates preflight request according to CORS specification: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ and https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your server should also respond to OPTIONS method (besides POST), and return Access-Control-Allow-Origin there too.
You can see it's the cause, because when your code creates request in Network tab (or in Fiddler proxy debugger) you should see OPTIONS request with ORIGIN header