Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Bill Shannon
10,327 PointsRunning local server?
I realize it may be easier to use workspaces, however I'd like to implement AJAX using a local express server. It may be beyond the scope of this course, but is there a fairly easy approach to doing that?
1 Answer
LaVaughn Haynes
12,397 PointsGetting set up with express was pretty easy. I just started this course http://teamtreehouse.com/library/express-basics
You can also check out installation instructions here http://expressjs.com/starter/installing.html
And the guide for serving static pages here (which is also easy) http://expressjs.com/starter/static-files.html
I did a simple test to see if I could run ajax and it worked. Here is the code. In my project folder I made a src folder. Inside that an app.js file and a public directory for my static files which contained my index.html file.
The comment in app.js is so my javaScript linter doesn't get confused by my node app code and mark it as syntax errors. This may not be necessary of you don't have a javaScript linter.
app.js
/* jshint node: true */
'use strict';
var express = require('express');
var app = express();
app.use(express.static('src/public'));
//route to json
app.get('/ajax', function(req, res){
res.send({
"text": "Running local server?",
"url": "https://teamtreehouse.com/community/running-local-server"
});
});
app.listen(3000, function(){
console.log('The frontend server is running on port 3000!');
});
public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax Express</title>
</head>
<body>
<h1>Results</h1>
<div class="result"></div>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$.get( "http://localhost:3000/ajax", function(data){
var dataText = data.text,
dataUrl = data.url;
$('.result').html('<a href="' + dataUrl + '" target="_blank">' + dataText + '</a>');
});
</script>
</body>
</html>
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsThe documentation that comes with the deployment should cover that?