2

I'm working through the React.js tutorial found here: http://facebook.github.io/react/docs/tutorial.html

When adding comments to the page using AJAX and the post method, I get 501 (Unsupported method ('POST')).

I know you can't send a JSON post command locally (similar to this question: angularjs $http.post results in 501 Unsupported method ('POST')) and I'm using python -m SimpleHTTPServer.

How do I set up a web service endpoint for the JSON file?

Community
  • 1
  • 1
joeyc
  • 55
  • 1
  • 6

1 Answers1

2

If you look at reactjs/react-tutorial on github, there's an example server using node.js:

git clone git@github.com:reactjs/react-tutorial.git && cd react-tutorial
npm install
node server.js

Here's the server.js file.

var fs = require('fs');
var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();

var comments = JSON.parse(fs.readFileSync('_comments.json'));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/comments.json', function(req, res) {
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(comments));
});

app.post('/comments.json', function(req, res) {
  comments.push(req.body);
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify(comments));
});

app.listen(3000);

console.log('Server started: http://localhost:3000/');

/**
 * This file provided by Facebook is for non-commercial testing and evaluation purposes only.
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Thanks for this! It's also good to note that this repo uses React 0.8 so the tutorial has changed a bit, but using a node with an express server did the trick. – joeyc Sep 26 '14 at 19:34
  • 1
    https://github.com/reactjs/react-tutorial is the new home of the tutorial-in-a-repo. – Paul O'Shannessy Sep 29 '14 at 17:57
  • I see you're good to go, but in case others come and see this before we get it updated, I added servers in a couple other languages (python, ruby) if node.js isn't your thing :) See the PR (and feel free to add suggestions in other languages!) - https://github.com/reactjs/react-tutorial/pull/5 – Paul O'Shannessy Sep 29 '14 at 19:51