I'm using Express.IO and This iOS Client trying to create a basic socket example but I can't seem to be able to connect.
I tried everything I could possibly find on google but everytime my client tries connecting I get the following error:
2013-08-12 14:48:42.628 SocketIOTest[59835:c07] ERROR: handshake failed ... Could not connect to the server.
2013-08-12 14:48:42.628 SocketIOTest[59835:c07] OnError: Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo=0x7594570 {NSErrorFailingURLStringKey=http://localhost:7076/socket.io/1/?t=16807, NSErrorFailingURLKey=http://localhost:7076/socket.io/1/?t=16807, NSLocalizedDescription=Could not connect to the server., NSUnderlyingError=0x10967bb0 "Could not connect to the server."}
When I go to http://localhost:7076/socket.io/1/?t=16807 in my browser I get this response:
ttIwyz7Tw6uFjp00WceI:60:60:websocket,htmlfile,xhr-polling,jsonp-polling
But for some reason when checking with header tools, it actually does return an HTTP 500 error. I'm really not sure why.
Here's my Node code:
#!/usr/bin/env node
var express = require('express.io');
var app = express().http().io();
var redisStore = require('connect-redis')(express);
app.use(express.cookieParser());
app.use(express.session({
store: new redisStore({
host: '192.168.33.10',
port: 6386
}),
secret: 'A>mVt*Cx87Kq^9:3}am$q67JYtGGAl'
})) ;
app.use(function(err, req, res, next){
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
response.header('Access-Control-Allow-Credentials', 'true');
response.header('Access-Control-Allow-Headers', 'Content-Type, Accept, Origin, Cookie');
next();
});
app.set( 'origins', '*' );
app.io.on('connection', function (socket) {
console.log("connection");
socket.emit('news', { hello: 'world' });
});
app.listen(7076);
console.log('App API Server is listening on port 7076');
Would appreciate any help on this.
it seems that you are referring to localhost: NSErrorFailingURLStringKey=http://localhost:7076/socket.io/1/?t=16807 in your IOS client, while the node.js server is running on some external Linux box.
Try connecting to the server instead.
Related
String url = "http://script.google.com/macros/s/" + GOOGLE_SCRIPT_ID + "/exec?" + data;
Serial.print(url);
HTTPClient https;
https.begin(url);
delay(200);
int httpsCode = https.GET();
I want to send the readed data from a MRFC555, tag and name to store it on google Sheet, but i'm facing some troubles with http request
when i use https the board reboot and when i use http i got "-1
[HTTP] GET... failed, error: connection refused"
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://bayut-api-v1:4000/properties/list?purpose=for-sale&locationExternalIDs=5002&sort=city-level-score&location=dubai&page=1. (Reason: CORS request did not succeed). Status code: (null).
I am using docker I built "API" and "FrontEnd with nextjs" dockerized all of that in a custom network
named "bayut"
and exposed port 80 with Nginx *using Nginx as a reverse proxy
the traffic comes on port 80 -> port 3000 which is the nextjs app
iam getting a cors error when I use the app from localhost
but when I try to use the firefox docker image inside my "bayut" network
everything works perfectly fine
API: http://bayut-api-v1:4000
FrontEnd http://client-bayut:3000 ->no cors error when I use this domain inside the bayut network
but when I access from localhost outside the bayut network iam getting a cors error
one possible solution is to use https://nextjs.org/docs/api-reference/next.config.js/rewrites
but that solution will expose my API and I want my API to privat
I will add my index page on the server side
import express from "express";
import { Request, Response, NextFunction, Application } from "express";
import { Server } from "http";
import createHttpError from "http-errors";
const Redis = require("ioredis");
const cors = require("cors");
const client = new Redis({
port: 6379,
host: "redis-bayut",
});
// const client = new Redis(6379, "172.17.0.3");
require("dotenv").config();
const app: Application = express();
const allowedOrigins = ["http://bayut-client:3000", "http://localhost:3000" ,"127.0.0.1:3000"];
app.use(cors({
origin: allowedOrigins,
methods: ["GET"],
}));
app.get("/", async (req: Request, res: Response) => {
res.send("Hello World3!🌏");
});
// Routes
app.use("/auto-complete", require("./routes/auto-complete"));
app.use("/properties", require("./routes/properties"));
app.use("/agencies", require("./routes/agencies"));
const acceptOnlyGetRequsets = (
req: Request,
_res: Response,
next: NextFunction
) => {
if (req.method !== "GET") {
return next(createHttpError(405, "Method Not Allowed"));
}
};
// accept Only Get Requsets
app.use(acceptOnlyGetRequsets);
app.use((req: Request, res: Response, next: NextFunction) => {
next(new createHttpError.NotFound());
});
const errorHandler = (
err: any,
req: Request,
res: Response,
next: NextFunction
) => {
res.status(err.status || 500);
res.send({
message: err.message,
status: err.status,
});
};
app.use(errorHandler);
const PORT = process.env.PORT || 4000;
const server: Server = app.listen(PORT, () =>
console.log(`=> http://localhost:${PORT}/
⌛ ${new Date().toLocaleTimeString("en-us", { timeStyle: "medium" })}
`)
);
export const redisClient = client;
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://bayut-api-v1:4000/properties/list?purpose=for-sale&locationExternalIDs=5002&sort=city-level-score&location=dubai&page=1. (Reason: CORS request did not succeed). Status code: (null).
This error means that:
You are making a cross-origin request
The request failed entirely
Because it was cross-origin and it failed entirely there is no response so there are no response headers that could include CORS permission to give your JS access to that data.
(I think other things could cause the null status, but its pretty clear what it means given the context of the rest of your question).
In short: The browser can't access the URL you gave it.
but that solution will expose my API and I want my API to privat
If you want client-side JavaScript to access the API then you must expose the API to the browser.
I cannot make post request (get works fine) with espruino.
I've already checked the documentation and it seems pretty equal
here is my code:
let json = JSON.stringify({v:"1"});
let options = {
host: 'https://******,
protocol: 'https',
path: '/api/post/*****',
method: 'POST',
headers:{
"Content-Type":"application/json",
"Content-Length":json.length
}
};
let post = require("http").request(options, function(res){
res.on('data', function(data){
console.log('data: ' + data);
});
res.on('close', function(data){
console.log('Connection closed');
});
});
post.end(json);
The espruino console only return the 'connection closed' console.log.
The node.js server console (hosted on heroku and tested with postman) dont return anything.
Obv the esp8266 is connected to the network
What you're doing looks fine (an HTTP Post example is here), however Espruino doesn't support HTTPS on ESP8266 at the moment (there isn't enough memory on the chips for JS and HTTPS).
So Espruino will be ignoring the https in the URL and going via HTTP. It's possible that your server supports HTTP GET requests, but POST requests have to be made via HTTPS which is why it's not working?
If you did need to use HTTPS with Espruino then there's always the official Espruino WiFi boards, or I believe ESP32 supports it fine too.
you're using a package called "http" and then trying to send a request over https. You should also log out 'data' in the res.close so you can get some errors to work with.
[update 1]
i found out that io.connect('http://xxxxx.herokuapp.com') actually send out a request on xxxxx.herokuapp.com port 3000:
the connection works if the request is WITHOUT port number. I didn't specify a port in my io.connect, How can i get rid of that?
Request URL:http://xxxxx.herokuapp.com:3000/socket.io/1/?t=1360853265439
Request Headersview source
Cache-Control:max-age=0
Origin:http://localhost:3000
Referer:http://localhost:3000/about
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
Query String Parametersview sourceview URL encoded
t:1360853265439
[update 2]
for comparison here is the HEAD of a successful connect when i run the java script from local file system
Request URL:http://xxxxx.herokuapp.com/socket.io/1/?t=1360854705943
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host :xxxxx.herokuapp.com
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
[update 3]
set port to 80 seems to be working
var socket = io.connect('http://xxxxx.herokuapp.com',{port:80});
[Question] I intend to have socket.io set up on one host to talk to a Rails app on another host. It all works fine when the client side Javascript was hosted on localhost:3000 to connect to Socket.io hosted on a node.js server on localhost:5000. It works as well when both client side Javascript and Socket.io hosted on Heroku on the same port.
socket_server.js hosted on XXXX.herokuapp.com
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
, i = 0
io.configure(function () {
io.set("origin = *");
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 100);
});
var port = process.env.PORT || 5000; // Use the port that Heroku provides or default to 5000
app.listen(port, function() {
console.log(">>>>>>socket server up and running on port: "+port);
});
function handler (req, res) {
fs.readFile(__dirname + '/socket.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading socket.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log(">>>>>>client connected through socket");
socket.emit('news', '>>>>>>server say hello to client', i);
console.log('>>>>>>server say hello to client' +'['+i+']')
socket.on('my other event', function (data) {
socket.emit('news', i);
i++;
console.log(data +'['+i+']');
});
});
if I put client side javascript in socket.html on XXXX.herokuapp.com same as socket.io it behave as expected.
<div id='sandbox'>sandbox</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('window.location.hostname');
$('#sandbox').append('<div> lora </div>');
socket.on('news', function (data, index) {
$('#sandbox').append('<div>' + data + ' ' + index + '</div>');
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
However if I put client side Javascript on Rails server on YYYY.herokuapp.com and try to connect to Socket.io server on xxx.herokuapp.com, it doesnt work. it managed to retreive socket.io.js on the server but io.connect('http://xxxxx.herokuapp.com') doesnt not get any response from the server.
<div id='sandbox'>sandbox</div>
<script src="http://xxxxx.herokuapp.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://xxxxx.herokuapp.com');
$('#sandbox').append('<div> lora </div>');
socket.on('news', function (data, index) {
$('#sandbox').append('<div>' + data + ' ' + index + '</div>');
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I read a few post point the solution to set io.set("origins = *") but this seems not working in this case as well.
Origins are set to * by default in socket.io. And it would be io.set("origin", "*"); but as this is the default value, you can just ignore this function.
I do notice that you also have var socket = io.connect('window.location.hostname') in your client side code, you problably ment: var socket = io.connect(window.location.hostname) without the single quotes. The heroku docs do recommend the use of io.set("polling duration", 100); But you set it to 100 instead of the advised 10.Other then that I don't see anything wrong with your code and it should just work.
If these fixes don't help then I would blame it on your hosting. Heroku is a really restrictive platform when it comes to deploying real-time applications. So it could be that they are messing something up here. I would suggest trying to deploy somewhere else like on nodejitsu.com which also supports WebSockets and does not impose any limits to polling to see if it works there for you.
Need to access a webservice using soapclient.I have the following settings.
ini_set('default_socket_timeout', 120);
$client = new SoapClient(
"http://example.com/OnlineOrderProcessingWS.asmx?WSDL",
array('proxy_host' => "proxy url",
'proxy_port' => proxy port
)
);
$param=array("varname1"=>'value1',"varname2"=>'value2');
$result = $client->CustomerOrder($param);
print_r($result);
Executing this script throwing
Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers.
The most common reason for this error seems to be a timeout while waiting on the service response. You already adjust your socket_timeout to 120, but might want to try an even higher value. How long does it take for the error to be returned?