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
Related
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
I'm trying to make a post request to my php code to get some data posted from nodejs but when i try to access the php file it works fine but in nodejs output it gives error to me and not posting data.
My nodejs
const request = require('request');
const notification_options = {
url: 'https://my-site.com/site/push',
json: true,
body: {
var1:"test1",
var2:"test2"
}
};
request.post(notification_options, (err, res, body) => {
if (err) {
return console.log(err);
}
console.log(`Status: ${res.statusCode}`);
console.log(body);
});
PHP Code (https://my-site.com/site/push) :
public function actionPush(){
var_dump($_POST);
}
Output :
Status code : 400
when I access my php file directly from my browser it works and it returns an empty array.
How i can solve this, i need data to be posted into my php and there i want to read them.
Thanks
I use php(laravel 5.8) to broadcast, and I use laravel-echo-server, it's work. But!!! recent I need to something by my self. And I write a socket service by ndoejs. This is my code
const jwt = require('jsonwebtoken');
const server = require('http').Server();
const io = require('socket.io')(server);
...
// ==== The question is here =====================
const Redis = require('ioredis');
const redis = new Redis({
port: REDIS_PORT,
host: REDIS_HOST,
password: REDIS_PASSWORD
});
redis.psubscribe('myTestChannel.*');
redis.on('pmessage', function(pattern, channel, message) {
console.log(channel, message);
const object_message = JSON.parse(message);
io.sockets.emit(channel, object_message.data);
});
// ==== The question is here =====================
io.sockets.use(function (socket, next) {
if (socket.handshake.query && socket.handshake.query.token){
// auth
} else {
next(new Error('Authentication error'));
}
}).on('connection', function(socket) {
console.log('==========connection============');
console.log('Socket Connect with ID: ' + socket.id);
socket.on('join', (data) => {
... do something
});
socket.on('disconnect', () => {
... do something
})
});
server.listen(LISTEN_PORT, function () {
console.log(`Start listen ${LISTEN_PORT} port`);
});
It's work, but running a long time, my php get a error message, phpredis read error on connection. I'm not sure the real reason. But I guess is about my socket, because I use laravel-echo-server is great.
I'm not sure my redis.psubscribe's position is right? Maybe this cause a long time connection and cause php read error on connection?
I should move the redis.psubscribe into on('connection') and unsubscribe when disconnection?
I want to know the redis.psubscribe is the main cause the problem? Thanks your help.
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.
i work on laravel 5.2 and i added vinkla/laravel-pusher to do real time chat app on my site but i faced this issue:
"JSON returned from webapp was invalid, yet status code was 200."
this my controller:
public function authMessageChat(Request $req)
{
$channelName = e($req->input('channel_name'));
$socketId = e($req->input('socket_id'));
$auth = $this->pusher->presence_auth($channelName, $socketId, auth()->user()->id);
return response($auth);
}
this is my script:
var pusher = new Pusher('{{env("PUSHER_KEY")}}', {
authEndpoint: '../auth',
auth: {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
params: {
id: currentUser.id
}
}
});
var channel = pusher.subscribe('{{$chatChannel}}');
channel.bind('pusher:subscription_error', function(PusherError){
console.log('PusherError' + PusherError);
});
channel.bind('new-message', function(data) {
console.log(data.sender);
)};
Pusher error:
#chrismou Thank you for your answer..
your answer is right and we can implement the solution in another way..
just go to your .env file and make:
APP_DEBUG=false
instead of
APP_DEBUG=true
Thank you
It looks like your app is returning the debugbar html as part of the json response.
Assuming it's the barryvdh/laravel-debugbar you're using, according to the documentation you can switch off the debug bar at runtime:
Config::set('laravel-debugbar::config.enabled', false);
I assume you'll need to add that prior to the response being sent, in the controller method/route you're using for the authentication endpoint (ie, the one you're calling the socket_auth method from)