Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could Not Connect to Local Server in Xcode

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);

 });

});
like image 842
cnichs27 Avatar asked Jan 15 '16 15:01

cnichs27


1 Answers

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.

like image 64
Boris Serebrov Avatar answered Sep 28 '22 07:09

Boris Serebrov