Reputation: 1
I'm trying to rename an album from "cars" to "car". But keep getting the following error. SyntaxError: Unexpected token a in JSON at position 1.
What could be the problem?
I'm using the following curl command:
-s -X POST -H "Content-Type: application/json" \-d { "album_name" : "Car" } http://localhost:8080/albums/cars/rename.json
And this is my server.js:
var express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser');
var app = express();
app.use(morgan('dev'));
var fs = require('fs'),
album_hdlr = require('./handlers/albums.js'),
page_hdlr = require('./handlers/pages.js'),
helpers = require('./handlers/helpers.js');
app.use(express.static(__dirname + "/../static"));
app.get('/v1/albums.json', album_hdlr.list_all);
app.get('/v1/albums/:album_name.json', album_hdlr.album_by_name);
app.get('/pages/:page_name', page_hdlr.generate);
app.get('/pages/:page_name/:sub_page', page_hdlr.generate);
app.get("/", function (req, res) {
res.redirect("/pages/home");
res.end();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post(function(req, res){
console.log(req.body);
res.end('want to update album name to '
+ req.body.album.new_name + "\n");
});
app.get('*', four_oh_four);
function four_oh_four(req, res) {
res.writeHead(404, { "Content-Type" : "application/json" });
res.end(JSON.stringify(helpers.invalid_resource()) + "\n");
}
app.listen(8080);
And my package.json:
{
"description": "Our Photo Sharing Application with static middleware",
"version": "0.0.2",
"private": true,
"dependencies": {
"async": "2.x",
"body-parser": "^1.18.3",
"express": "4.x",
"morgan": "1.x",
"multer": "1.x",
"typescript": "^2.0.0"
}
}
Upvotes: 0
Views: 1826
Reputation: 47
Could it be that the cURL request isn't correctly passing the information in the body request?
I have a batch file that uses cURL to the make a POST request. The syntax I use to get the body to post correctly is the second syntax from Amirr0r's answer. I tried reformatting the -d portion of my file to use single quotes and not escape the double quotes with the body, but it didn't pass the value correctly.
So, if you structure the body portion of your cURL call like the answer above, it should correctly pass the data in.
Upvotes: 0
Reputation: 390
Try using single quotes like this:
curl -s -X POST -H "Content-Type: application/json" -d '{ "album_name" : "Car" }' http://localhost:8080/albums/cars/rename.json
Or use double quotes with escaping the inner double quotes
curl -s -X POST -H "Content-Type: application/json" -d "{ \"album_name\" : \"Car\" }" http://localhost:8080/albums/cars/rename.json
Also I don't understand why are you escaping "-d". It is not necessary.
Upvotes: 1
Reputation: 2203
in your curl command, the double quote might have be evaluated, try
-s -X POST -H "Content-Type: application/json" \-d '{ "album_name" : "Car" }' http://localhost:8080/albums/cars/rename.json
Upvotes: 2