Good morning,
Trying on the physical server, the request does not return with the statusText which instead works perfectly in the localhost.
Example code js (framework7):
statusCode: {
401: (xhr) => {
console.log(xhr.statusText)
//other code
in php:
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
die(header("$protocol 401 Error auth."));
Is there some setting in the php.ini that I am missing to return the text correctly to the server?
Seems like work only with that pattern:
http_response_code(401);
print_r('Error auth.');
exit;
xhr.responseText instead of xhr.statusText
Related
I am trying to call a simple php file from my React application which will send an email with the details from a contact form. For some reason when the React code executes the fetch of the PHP file, it returns a 409. However, if I manually post the URL into another tab it works as expected, and subsequent calls from my React application then work as expected!
This is my React code:
var url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg
console.log(url)
console.log('sending')
fetch(url,
{
'headers': {
'Accept': 'text/html',
'Content-Type': 'text/html'
},
'method': 'GET',
})
.then(
(result) => {
console.log(result.status)
if (result.status === 200) {
console.log('success')
this.togglePop();
this.setState({
name: "",
email: "",
phone: "",
message: "",
terms: false,
})
} else {
console.log('failed')
this.setState({ openError: true })
}
},
(error) => {
console.log('ERROR')
console.log(error)
this.setState({ openError: true })
}
)
And this is my PHP file:
<?php
//header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html');
// error handler function
function customError($errno, $errstr) {
error_log($errstr);
http_response_code(500);
}
// set error handler
set_error_handler("customError");
http_response_code(200);
// send email
mail($_GET["to"],$_GET["subject"],$_GET["msg"],"From: donot.reply#site.co.uk","-f donot.reply#site.co.uk");
error_log($_GET["subject"].":\n".$_GET["msg"], 0);
echo 'OK';
?>
I have spent several days trying to figure out why this is happening. My htaccess file seems OK as once I have made one succesful call to the PHP file it works after that!
It's not a CORS issue as the file is on the same domain.
Anyone got any ideas?
You are sending the wrong request to the server, and that's why you get a 409 error. You should encode the URL params before sending a request
const url = '/backend/sendmail.php?subject=New Website Enquiry&to=info#site.co.uk&msg=' + msg;
const encoded = encodeURI(url);
console.log(encoded)
// expected correct URI: "/backend/sendmail.php?subject=New%20Website%20Enquiry&to=info#site.co.uk&msg="
You can read more about it here
I'm using XAMPP for API
I have this error in console:
Network Error
- node_modules\axios\lib\core\createError.js:15:17 in createError
- node_modules\axios\lib\adapters\xhr.js:80:22 in handleError
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
With the simple code:
const apiAsyncTest = async () => {
try {
const response = await axios.get('https://127.0.0.1/api/api.php');
console.log(response);
} catch (error) {
console.log(error);
}
}
apiAsyncTest();
Already checked the internet of the android emulator, I changed the "127.0.0.1" to "localhost" https to http, but nothing works
My page api code contains simple code too:
<?php
echo 'test';
But I tried it on another website and I got it successfully
Got it! I changed "localhost" to my IPV4 and work successfully
I am at a loss now. I am trying to reach the Azure Billing & Usage API via my php application, but keep getting the following error:
XMLHttpRequest cannot load
https://ea.azure.com/rest/{agreementnumber}/usage-reports. 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' is therefore not allowed access.
I know the link mentions the url is https://consumption.azure.com/v2/enrollments, however this was not working for me and after contact with Azure tech service I needed to use the older ea.azure.com entry point.
I am trying this from my development xampp localhost server as well as the production server (live intranet solution), but to no avail. Using postman the connection succeeds and I receive a valid response from the API.
Basically the API requires only an API key, which i have. no authorization is required next to this.
As Postman is succesful in getting a valid response from the API, I used their code generator to get me:
php script
javascript script
jquery ajax script
All of them return the same error for me; the jquery ajax one is shown because that one is preferred:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://ea.azure.com/rest/<?php echo $agreement_number; ?>/usage-reports",
"method": "GET",
"dataType": 'json',
"headers": {
"authorization": "bearer <?php echo $key; ?>"
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connected.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
I do not understand why Postman is able to connect to the API and retrieve it's information, whilst exactly the same code generates a CORS error when used in my application.
Could this have something to do with my application being hosted in an internal virtual machine within the company's network, not accessible from the internet?
Edit: Rory mentioned the tight security restrictions of JS - therefore I added the php script also. As I use php 5.6, I do not have the class httpRequest by default, so I used the httpRequest class by twslankard and tweaked it to accept custom headers like this (added public function):
public function setHeaders($headers) {
if(is_array($headers)) {
foreach($headers as $name => $val) {
$this->headers[$name] = $val;
}
}
}
And calling the class like this:
include_once($_SERVER['DOCUMENT_ROOT'].'/functions/class_httprequest.php');
$request = new HttpRequest($url, 'GET');
$request->setHeaders(array(
'api-version' => '2014-09-02',
'authorization' => $key
));
try {
$response = $request->send();
echo $request->getStatus().'<br>';
echo $request->getResponseBody();
} catch (HttpException $ex) {
echo $ex;
}
Using the php version it did work, the trick was adding the api-version header, before that I got an http 400 error back using the php script.
Using the php version it did work, the trick was adding the api-version header, before that I got an http 400 error back using the php script.
newbie question. I have a web page sending $_POST data to a php script on a server.
How to debug php (see the output of echo) ?
If I just browse to the www.serveradress.com/myscript.php,I see nothing...
I am using Chrome.
Thanks
Edit: I am using ngFileUpload on the client side.
Edit: I see that the file is well received because I see it on the server with filezilla.
client side:
$scope.uploadBoardPic = function(file, errFiles) {
$scope.boardPic = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: 'http://myserver.com/angular-seed/appendBoardPicture.php',
method: 'POST',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}
server side:
<?php
$filename = $_FILES['file']['name'];
$destination = './' . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
echo "<pre>" . print_r($_FILES, true) . "</pre>";
?>
Php keeps POST variables within the $_POST global. You should be able to run something to the affect of
echo "<pre>" . print_r($_POST, true) . "</pre>";
To get back the debugging information you need. This of course will only work if you are doing a valid POST via a form. That meaning that the page is actually going to change. Looking at your question though, it looks like you are working in all javascript for your post/reply. In that case, you will want to look for the reply information from php, within your javascript. You can do this by looking at the network tab, during the submission.
As a good practice, you should use error logs for this kind of task. If you have not set up a error log then you should set it up in the apache config file.
Once you set the error log simply type this:
error_log(var_export($_POST, true));
and you can see the exports in your error log.
http://php.net/manual/en/function.error-log.php
I'm trying to send a post request but It is not sending. I dont get output in the console log of the browser.
My node server.js is running in x.x.x.x:8000 then I connect it with my client.html. x.x.x.x:8000/client.html
Here is my node.js server.
function handler (req, res) {
var filepath = '.' + req.url;
if (filepath == './')
filepath = './client.html';
var extname = path.extname(filepath);
var contentType = 'text/html';
switch(extname){
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filepath, function (exists){
if (exists){
fs.readFile(filepath, function(error, content){
if(error){
res.writeHead(500);
res.end();
}
else{
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
}
else{
res.writeHead(404);
res.end();
}
});
}
JAVASCRIPT CODE - I'm using ajax call and sending request to COMMAND.php
$.post(
'/var/www/COMMAND.php',
{ cmd: "OUT" },
function( data ){
console.log(data);
});
PHP COMMAND.php - This writes to the the named pipe in linux. When it is done writing it echo success.
<?php
if ($_POST['cmd'] === 'OUT') {
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "OUT\n");
fclose($con);
echo "SUCCESS";
exit;
}
?>
Why is it not sending any post requests to COMMAND.php? Is there any way for me to call COMMAND.php and execute the commands in it?
Because NodeJS runs JS, not PHP. Also, unlike Apache which has a built-in file handling, in NodeJS, you need to build code or use an existing library to route your urls to files.
As for your question, it's either you:
Setup another server to execute that PHP. Your AJAX is calling to your NodeJS server. You could route that request from NodeJS to your PHP server (Apache or whatever), basically making NodeJS act like a proxy.
Or create code in JavaScript for NodeJS that runs a similar routine as your PHP script, and you won't need PHP or another server anymore.