Trying to Connect to a local server from Xcode. I have imported an Alamofire Pod into my Xcode project and run the following command in xcode
Alamofire.request(.GET, "http://localhost:3000" , parameters: ["code": "123"]).responseJSON {
response in
print ("Hello", response)
}
I recieve the following error in Xcode when running on iOS device.
FAILURE: Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the server." UserInfo={NSUnderlyingError=0x13d84f7f0 {Error Domain=kCFErrorDomainCFNetwork Code=-1004 "(null)" UserInfo={_kCFStreamErrorCodeKey=61, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=http://localhost:3000/, NSErrorFailingURLKey=http://localhost:3000/, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=61, NSLocalizedDescription=Could not connect to the server.}
I know the local is serving is running. When I call the following function on the command line:
$ node index.js
Running at http://localhost:3000
In the browser the following is shown:
Cannot GET /
My .js file is the following:
var buffer = require('buffer');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var express = require('express');
var request = require('request');
var url = require('url');
var app = express();
var config = {
clientId: '',
clientSecret: '',
callbackUrl: '',
encryptionSecret: '',
endpoint: 'https://accounts.spotify.com',
};
var secretString = config.clientId + ':' + config.clientSecret;
var authHeader = 'Basic ' + new buffer.Buffer(secretString).toString('base64');
// app.use(bodyParser.urlencoded({ extended: false })); // TODO - Figure out why this should be here
app.use(bodyParser.json()); // TODO - Figure out why this should be here
var server = app.listen(3000, function() {
var address = server.address();
console.log('Running at http://localhost:%s', address.port);
});
app.post('/swap', function(req, res) {
console.log(req.body);
if (!req.body || !req.body.hasOwnProperty('code')) {
console.log('Swap: missing auth code');
res.status(550).send('Permission Denied');
return;
}
formData = {
grant_type: 'authorization_code',
redirect_uri: config.callbackUrl,
code: req.body.code
};
console.log('Swap: POST to %s', url.resolve(config.endpoint, '/api/token'), formData);
request.post({
url: url.resolve(config.endpoint, '/api/token'),
headers: {
'Authorization': authHeader,
'Content-Type': 'application/x-www-form-urlencoded',
},
form: formData,
}, function(error, response, body) {
if (error) {
console.log('Swap: Error - ', error);
res.status(500).send('Internal Server Error');
return;
}
if (res.statusCode != 200) {
debug('Swap: response: ', response.statusCode);
res.status(550).send('Permission Denied');
return;
}
var tokenData = JSON.parse(body);
console.log('Swap: tokenData - ', tokenData);
res.status(200).set({
'Content-Type': 'application/json',
}).send(tokenData);
});
});
Here is the summary of the discussion from comments:
1) Initially the node.js application only had a route for POST requests. This makes debugging more complex. Add a route for GET requests, so you can check http://localhost:3000 from the browser. Now check if it works in the desktop browser and in the simulator browser to confirm the general node application availability.
2) Address like http://localhost:3000 or http://127.0.0.1:3000 only works on the same machine where the node.js application is running. This includes the iOS simulator, but will not work with such address on the device.
3) To test on the device - replace the localhost address with your local network IP address. The local network address usually looks like 192.168.xxx.xxx and can be found in network settings.
To actually run this setup in production, you will need a server, where you run the node.js application, to have a public real IP address or domain name and you will connect to it using something like http://my.app.domain.or.ip:3000.
Related
I'm trying to get data in JSON format. I just copied an old project and changed it IP address to database, username, port, password and database name.
When I try to access data through this addres: localhost:3000/&id=13
The browser just doesn't load them.
When I enter the address with the port without / I see the message with error:
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
The same code is pinned to another database and I see the data in JSON format.
I checked 10 times if the username, password, port and database name are correct and they are fine.
The code:
// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')
app.use(cors())
// Server port
var HTTP_PORT = 3000
var pool = mysql.createPool({
connectionLimit: 10,
host: '192.168.0.1',
user: 'user',
port: '3388',
password: 'password',
database: 'databasename'
});
var ardaforecast = '';
app.route('/')
.get(function (req, res) {
// omitted
res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
//const date = req.query.date;
const id = req.query.id;
pool.query(`CALL Get_Alert_levels_Station(${id})`, function (error, result) {
if (error)
return res.status(500).json({ error: "Грешна заявка. Опитай отново !"})
aladinModel = result;
res.json({ ardaforecast })
});
});
// Start server
app.listen(HTTP_PORT, () => {
console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});
pool.on('error', function (err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
app.use(function (req, res) {
res.status(404);
})
;
Can I get an example of how I can fix this or how to find out where the problem is ?
You can use this one to see how what your url contains: https://www.freeformatter.com/url-parser-query-string-splitter.html
In your example, the problem is that you're using & (ampersand), but what it does is separating multiple query parameters. Since you have just one, your url is not properly structured and does not contain any parameters whatsoever.
You should use ? (question mark) to denote the first one:
localhost:3000/?id=13
p.s. Успех ;)
I have been able to connect to my proxy using their source code which is like this with personal data omitted:
'use strict';
var http = require('http');
var port = process.env.PORT || 1337;
var url = require('url');
var dirlevel = '..';
var runPup = require('./mypuppeteerscript.js');
http.createServer(function (req, res) {
var page = req.url;
var request = require('request');
request({
uri: 'http://httpbin.org/get',
proxy: 'http://<my api key>:#proxy.crawlera.com:8011'
}, function callback(error, response, body) {
console.log(body);
});
runPup.runPuppeteer(page);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('My App - Alpha\nProcessing File\n' + page);
}).listen(port);
The following is the block that was pasted from the Zyte website:
var request = require('request');
request({
uri: 'http://httpbin.org/get',
proxy: 'http://<my api key>:#proxy.crawlera.com:8011'
}, function callback(error, response, body) {
console.log(body);
});
Unfortunately, that does not result in every request from my Puppeteer script being routed through the proxy. How would I modify this code so that every request from runPup.runPuppeteer(page) is routed through the proxy?
My options are somewhat limited here because Zyte cannot be accessed via Puppeteer directly due to my Puppeteer version being greater than 1.17. To use Zyte in my Puppeteer code I would need to install Docker on my Windows Server. I have never used Docker and my time is limited.
I am attempting to use a Nodejs server as a proxy server to get around CORS of specific API's, such as darksky.net or googleapis. As shown in my Angular 8 code below, I try to send a get request to my NodeJS server, passing three parameters. Once the NodeJs server has received these parameters, I request the API, but I get a 404 error in return.
Angular code:
this.http.get('search/coords/',
{
params: {
address: this.street,
city: this.city,
state: this.state
}
}).subscribe(data => {
this.lattitude = data['results']['geometry']['location']['lat'];
this.longitude = data['results']['geometry']['location']['lon'];
console.log(this.lattitude);
console.log(this.longitude);
this.coords = {
lat: this.lattitude,
lon: this.longitude
};
});
return this.coords;
}
And here is my current Nodejs/Express code:
const express = require('express')
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
var request = require('request');
const app = express();
var url = "";
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'false'}));
app.use(cors());
app.get('search/coords/', function (req, res) {
var street = req.query.address;
var city = req.query.city;
var state = req.query.state;
url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + street + "," + city + "," + state + "&key=blah/"
request(url, function(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
res.send(info);
}
})
});
Specifically, I receieve a GET 404 not found error and an ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/search/coords/?address......." I'm new to angular and nodejs, so any help would be much appreciated.
There are two problems:
First is that you did not start the Node server
Second is that if you call this.http.get('search/coords', ...) then the default domain for that request is the current one, which is http://localhost:4200 and that is not you Node server port.
To make it work, you need to address both of the above.
So firstly, add this code to the Node.js server file (at the very bottom) to make it listen on some port:
app.listen(3000, () => {
console.log('Listening on port', 3000);
});
Then, modify your Angular code to make it look like this:
this.http.get('http://localhost:3000/search/coords/', ....);
It should work that way.
I'm having a trouble on looking for the error can anyone point it out for me please i have been into this for 2 days and still can't figure it out.
the picture above is the error log from heroku.
and here is my server.js for the ice configuration
// Load required modules
var http = require("http"); // http server core module
var https = require('https');
var express = require("express"); // web framework external module
var serveStatic = require('serve-static'); // serve static files
var socketIo = require("socket.io"); // web socket external module
var easyrtc = require('./lib/easyrtc_server'); // EasyRTC external module
// Set process name
process.title = "node-easyrtc";
// Setup and configure Express http server. Expect a subfolder called "static" to be the web root.
var app = express();
app.use(serveStatic('public', {'index': ['index.html']}));
var port = process.env.PORT || 8080;
// Start Express http server on port 8080
var webServer = http.createServer(app).listen(port);
// Start Socket.io so it attaches itself to Express server
var socketServer = socketIo.listen(webServer, {"log level":1});
easyrtc.setOption("logLevel", "debug");
// Overriding the default easyrtcAuth listener, only so we can directly access its callback
easyrtc.events.on("easyrtcAuth", function(socket, easyrtcid, msg, socketCallback, callback) {
easyrtc.events.defaultListeners.easyrtcAuth(socket, easyrtcid, msg, socketCallback, function(err, connectionObj){
if (err || !msg.msgData || !msg.msgData.credential || !connectionObj)
{
callback(err, connectionObj);
return;
}
connectionObj.setField("credential", msg.msgData.credential, {"isShared":false});
console.log("["+easyrtcid+"] Credential saved!", connectionObj.getFieldValueSync("credential"));
callback(err, connectionObj);
});
});
// To test, lets print the credential to the console for every room join!
easyrtc.events.on("roomJoin", function(connectionObj, roomName, roomParameter, callback) {
console.log("["+connectionObj.getEasyrtcid()+"] Credential retrieved!", connectionObj.getFieldValueSync("credential"));
easyrtc.events.defaultListeners.roomJoin(connectionObj, roomName, roomParameter, callback);
});
// Start EasyRTC server
var rtc = easyrtc.listen(app, socketServer, null, function(err, rtcRef) {
console.log("Initiated");
rtcRef.events.on("roomCreate", function(appObj, creatorConnectionObj, roomName, roomOptions, callback) {
console.log("roomCreate fired! Trying to create: " + roomName);
appObj.events.defaultListeners.roomCreate(appObj, creatorConnectionObj, roomName, roomOptions, callback);
});
});
//ice config easyrtc
easyrtc.on("getIceConfig", function(connectionObj, callback) {
// This object will take in an array of XirSys STUN and TURN servers
var iceConfig = [];
http.request({
url: 'https://service.xirsys.com/ice',
qs: {
ident: "***",
secret: "****",
domain: "***",
application: "test-livestream",
room: "test-livestream-room",
secure: 1
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
// body.d.iceServers is where the array of ICE servers lives
iceConfig = body.d.iceServers;
console.log(iceConfig);
callback(null, iceConfig);
}
else
{
console.log(error);
}
}
});
});
//listen on port 8080
webServer.listen(8080, function () {
console.log('listening on http://localhost:'+port);
});
By adding another module
var request = require("request");
and editting my ice server
request.post('https://service.xirsys.com/ice',{
form:{
ident: "****",
secret: "****",
domain: "****",
application: "****",
room: "****",
secure: 1
},
json:true
},
i obtain to let it work :)
I'm trying to create an HTTP/S MitM forwarding proxy using Node.js.
The way I'm tackling this project is by reusing the solution found in ./lib/proxy.js file of the NPM Proxy Cache project created by #runk after he raised the issue on the Node HTTP Proxy project issue tracker.
My Proxy() class looks like this:
var request = require('request')
, https = require('https')
, http = require('http')
, net = require('net')
, url = require('url')
, os = require('os')
, fs = require('fs');
var SOCKET_PATH = os.tmpdir() + 'mitm.sock';
console.log('[SOCKET PATH] ' + SOCKET_PATH);
function Proxy (config) {
config = config || {};
if(fs.existsSync(SOCKET_PATH)) {
fs.unlinkSync(SOCKET_PATH);
}
var options = {
key: fs.readFileSync('./certs/dummy.key', 'utf8'),
cert: fs.readFileSync('./certs/dummy.crt', 'utf8')
};
// HTTPS Server
https.createServer(options, this.handler).listen(config.port + 1, this.hostname, function (e) {
if(e) {
console.log('[HTTPS] Server listen() error !');
throw e;
}
});
// HTTP Server
var server = http.createServer(this.handler);
server.listen(config.port, this.hostname, function (e) {
if(e) {
console.log('[HTTP] Server listen() error !');
throw e;
}
});
// Intercept CONNECT requests for HTTPS handshake
server.addListener('connect', this.httpsHandler);
}
Proxy.prototype.handler = function (req, res) {
var schema = !!req.client.pair ? 'https' : 'http'
, path = url.parse(req.url).path;
var dest = schema + '://' + req.headers['host'] + path;
console.log('(1) - [' + schema.toUpperCase() + '] ' + req.method + ' ' + req.url);
var params = {
rejectUnauthorized: false,
url: dest
};
if(req.method.toUpperCase() !== 'GET') {
return console.log('[HTTP] Request is not HTTP GET.');
}
var onResponse = function (e, response) {
if(e == null && response.statusCode === 200) {
return r.pipe(res);
}
var body = 'Status ' + response.statusCode + ' returned';
if(e) {
body = e.toString();
}
res.end(body);
};
var r = request(params);
r.on('response', onResponse.bind(null, null));
r.on('error', onResponse.bind(null));
};
Proxy.prototype.httpsHandler = function (request, socketRequest, bodyHead) {
var httpVersion = request['httpVersion']
, url = request['url'];
console.log('(2) - [HTTPS] ' + request['method'] + ' ' + request['url']);
var proxySocket = new net.Socket();
// ProxySocket event handlers
proxySocket.connect(SOCKET_PATH, function () {
proxySocket.write(bodyHead);
proxySocket.write('HTTP/' + httpVersion + ' 200 Connection established\r\n\r\n');
});
proxySocket.on('data', function (chunk) {
console.log('ProxySocket - "data"');
socketRequest.write(chunk);
});
proxySocket.on('end', function () {
console.log('ProxySocket - "end"');
socketRequest.end();
});
proxySocket.on('error', function (e) {
console.log('ProxySocket - "error"');
console.log(e);
console.log(e.stack);
socketRequest.write('HTTP/' + httpVersion + ' 500 Connection error\r\n\r\n');
socketRequest.end();
});
// SocketRequest event handlers
socketRequest.on('data', function (chunk) {
console.log('SocketRequest - "data"');
proxySocket.write(chunk);
});
socketRequest.on('end', function () {
console.log('SocketRequest - "end"');
proxySocket.end();
});
socketRequest.on('error', function (e) {
console.log('socketRequest - "error"');
console.log(e);
console.log(e.stack);
proxySocket.end();
});
};
module.exports = Proxy;
And my Index.js file that start my program looks like this:
var Proxy = require('./lib/proxy');
var proxy = new Proxy({
hostname: '127.0.0.1',
port: 8000
});
Here's my directory / file structure this:
/my_project
/certs
dummy.crt // Copied from the NPM Proxy Cache project
dummy.csr // Copied from the NPM Proxy Cache project
dummy.key // Copied from the NPM Proxy Cache project
/lib
proxy.js
index.js
I'm testing my program by setting (in Mac OSX Maverick) an HTTP and HTTPS proxy as IP address 127.0.0.1 and port 8000.
When browsing an HTTP only website everything works fine, but if I browse an HTTPS website I get the following error:
{[Error: connect ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'connect'}
Error: connect ENOENT
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
Any ideas from where this issue could come from and how to fix this ?
Thank you very much in advance !
(If you want to test my code, the NPM module request is the only dependency needed to run the code.)
EDIT: The certs can be downloaded from here : https://github.com/runk/npm-proxy-cache/tree/master/cert.
I'm an author of npm-proxy-cache. In fact I've created another project called thin https://www.npmjs.org/package/thin and I hope in future the npm proxy cache thing will utilize it. Despite the fact that it's still very rough it's usable and it does what you need.
E.g.
proxy code
var Thin = require('thin')
var proxy = new Thin;
// `req` and `res` params are `http.ClientRequest` and `http.ServerResponse` accordingly
// be sure to check http://nodejs.org/api/http.html for more details
proxy.use(function(req, res, next) {
console.log('Proxying:', req.url);
next();
});
// you can add different layers of "middleware" similar to "connect",
// but with few exclusions
proxy.use(function(req, res, next) {
if (req.url === '/foobar')
return res.end('intercepted');
next();
});
proxy.listen(8081, 'localhost', function(err) {
// .. error handling code ..
});
server code
var express = require('express'); // v3.4
var app = express();
app.use(express.urlencoded({limit: '10mb'}));
app.get('/test', function(req, res){
console.log(req.protocol, 'get req.query', req.query);
res.end('get: hello world');
});
app.post('/test', function(req, res) {
console.log(req.protocol, 'post req.query', req.query);
console.log(req.protocol, 'post req.body', req.body);
res.end('post: hello world');
});
app.listen(3000);
var fs = require('fs');
var https = require('https');
https.createServer({
key: fs.readFileSync('./cert/dummy.key'), // your mitm server keys
cert: fs.readFileSync('./cert/dummy.crt')
}, app).listen(3001);
You need to start proxy and server in two terminal sessions, then
curl -d "foo=baz" -k -x https://localhost:8081 https://localhost:3001/test?foo=bar
curl -d "foo=baz" -x http://localhost:8081 http://localhost:3000/test?foo=bar
After that you should be able to see following output from the server
https post req.query { foo: 'bar' }
https post req.body { foo: 'baz' }
http post req.query { foo: 'bar' }
http post req.body { foo: 'baz' }
Small example for interceptor
curl -d "foo=baz" -k -x https://localhost:8081 https://localhost:3001/foobar
It should return intercepted
Hope that helps :)