I am trying to create an API using a local server for testing. The route
'GET' works fine, however 'POST' has a problem and it is returning 'Cannot GET /add/name'. I am developing the API using node.js and Express. Why am I receiving get when the route is set to 'POST'? Where is the problem?
var fs = require('fs');
var data = fs.readFileSync('events.json');
var allEvents = JSON.parse(data);
console.log(allEvents);
console.log('Server running.');
var express = require('express');
var app = express();
var sever = app.listen(3000, listening);
function listening() {
console.log('Serving...');
}
app.use(express.static('website'));
//GET and send all data from JSON
app.get('/all', sendAll);
function sendAll(request, response) {
response.send(allEvents);
}
//POST new data to JSON
app.post('/add/:name', addData);
function addData(request, response) {
var newData = request.params;
var name = newData.name;
var eventType = newData.eventType;
var reply;
// var newEvent = {
// name: ":name",
// eventType: ":eventType",
// };
var newData = JSON.stringify(allEvents, null, 2);
fs.writeFile('events.json', newData, finished);
function finished(err) {
console.log('Writting');
console.log(err);
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
Request
$(function() {
//HTML
var $list = $('#list');
var jsonURL = '../events.json'
$.ajax({
type: 'GET',
url: '/all',
success: function(data) {
console.log('Data received', data);
$.each(data, function (type, string) {
$list.append('<li>' + type + " : " + string + '</li>');
});
},
error: function (err) {
console.log('Error, data not sent.', err);
}
});
$('#submit').on('click', function () {
// var newEvent = {
// name: $name.val(),
// eventType: $eventType.val(),
// };
var name = $('#fieldName').val();
var eventType = $('#fieldEventType').val();
console.log(name);
$.ajax({
type: 'PUT',
url: '/add/' + name,
success: function (addData) {
$list.append('<li>name: ' + name + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
});
Thank you in advance.
For testing POST request, you can use Postman to test it. If you use the browser to call the api, it will be GET method instead of POST.
Related
I send data from one server to another with XMLhttpRequest but this code doesn't work:
var AjaxURL = 'http://localhost:5000/index.html';
$.ajax({
type: "GET",
url: AjaxURL,
data: {
foo: "test01"
},
success: function(result) {
window.console.log('Successful');
}
});
(Console log:
"Successful")
I have tried it with an iframe and it works but I need to send it with ajax or XMLhttpRequest.
const socket = io();
let params = new URLSearchParams(location.search);
let a1 = params.get('foo');
socket.emit('data', a1);
socket.on('data', (data) => {
const fileName = './src/data.json';
const file = require(fileName);
file.data = data;
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log('writing to ' + fileName + ':' + data);
});
})
{"data":"testing"}
Thanks
I'm running express node server and i use
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
to GET data inside json on the server.
json with data looks like:
[
{
"id": 1453464243666,
"text": "abc"
},
{
"id": 1453464256143,
"text": "def"
},
{
"id": 1453464265564,
"text": "ghi"
}
]
How (what request to perform) to delete\modify any object in this json?
To read the JSON file, you can make use of the jsonfile module. You then need to define a put route on the express server. A snippet of code for the express server highlighting the vital parts:
app.js
// This assumes you've already installed 'jsonfile' via npm
var jsonfile = require('jsonfile');
// This assumes you've already created an app using Express.
// You'll need to pass the 'id' of the object you need to edit in
// the 'PUT' request from the client.
app.put('/edit/:id', function(req, res) {
var id = req.params.id;
var newText = req.body.text;
// read in the JSON file
jsonfile.readFile('/path/to/file.json', function(err, obj) {
// Using another variable to prevent confusion.
var fileObj = obj;
// Modify the text at the appropriate id
fileObj[id].text = newText;
// Write the modified obj to the file
jsonfile.writeFile('/path/to/file.json', fileObj, function(err) {
if (err) throw err;
});
});
});
app.put('/edit/:id', (req,res) => {
var id = req.params.id;
var fname = req.body.fname;
var lname = req.body.lname;
var age = req.body.age;
var address = req.body.address;
var phone = req.body.phone;
jsonfile.readFile("./users.json", function(err,data) {
var fileObj = data;
fileObj.users_array.map((curr) => {
if(curr.id == id) {
curr.fname = fname;
curr.lname = lname;
curr.age = age;
curr.address = address;
curr.phone = phone;
}
});
jsonfile.writeFile('./users.json', fileObj, function(err) {
if(err) throw err;
});
});
I have a swift project in which i want use push notifications. I tried use parse server using a job schedule with .js files. The problem is that when i run the job on job status window i get this error:
"TypeError cannot read property 'entry' of undefined at main.js at 39:27"
Here is my main.js file:
var xmlreader = require('cloud/xmlreader.js');
var url = "http://www.ilsecoloxix.it/homepage/rss/homepage.xml";
function SavePost(title, link){
var PostClass = Parse.Object.extend("Post");
var post = new PostClass();
post.set("title", title);
post.set("link", link);
post.save();
}
function SendPush(title, link){
var query = new Parse.Query(Parse.Installation);
Parse.Push.send({
where: query,
data: {
url: link,
alert: title,
sound: "default"
}
}, {
success: function() {
SavePost(title, link);
response.success("Push sent to everyone");
},
error: function(error) {
response.error("Error sending push: "+error);
}
});
}
Parse.Cloud.job("fetchPosts", function(request, response) {
Parse.Cloud.httpRequest({
url: url,
success: function(httpResponse) {
xmlreader.read(httpResponse.text, function (err, res){
var newPost = res.feed.entry.at(0);
var title = newPost.title.text();
var link = "";
newPost.link.each(function (i, linkObj){
if (linkObj.attributes().rel == "alternate"){
link = linkObj.attributes().href;
}
});
var PostClass = Parse.Object.extend("Post");
var query = new Parse.Query(PostClass);
query.equalTo("link", link);
query.find({
success: function(results) {
console.log(results);
if (results.length == 0){
SendPush(title, link);
} else {
response.error("Post already pushed");
}
}
});
});
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error("Error fetching posts from feed");
}
});
});
How can i avoid this problem?
I am using Fiddler to display xml and find no feed node, should be res.rss.channel
http://www.ilsecoloxix.it/homepage/rss/homepage.xml
Response data res.feed is undefined. You can console.log(res) to figure out what is wrong. Also make sure the signature is correct for xmlreader.read(httpResponse.text, function (err, res), not sure why err is the first parameter of the function, most likely res is the first.
if(res && res.feed && res.feed.entry){
var newPost = res.feed.entry.at(0);
var title = newPost.title.text();
var link = "";
newPost.link.each(function (i, linkObj){
if (linkObj.attributes().rel == "alternate"){
link = linkObj.attributes().href;
}
});
var PostClass = Parse.Object.extend("Post");
var query = new Parse.Query(PostClass);
query.equalTo("link", link);
query.find({
success: function(results) {
console.log(results);
if (results.length == 0){
SendPush(title, link);
} else {
response.error("Post already pushed");
}
}
});
});
}
I am using azure mobile services, with following custom API:
var returnVal = new Object;
exports.post = function (request, response) {
// Use "request.service" to access features of your mobile service, e.g.:
// var tables = request.service.tables;
// var push = request.service.push;
var merchantdetailsTable = request.service.tables.getTable("merchantdetails");
var resourceName;
//console.log(JSON.stringify(request.parameters));
merchantdetailsTable.insert({
name: request.body.workerNameInput,
emailid: request.body.workerEmailIDInput,
contact: request.body.workerContactNumberInput
}).then(function (merchantInserted) {
returnVal.workerId = merchantInserted.id;
resourceName = returnVal.workerId.toLowerCase();
var shopworkersTable = request.service.tables.getTable("shopworkers");
return shopworkersTable.insert({
id: merchantInserted.id,
shopid: request.body.shopId
});
}, function(err){
return response.send(statusCodes.INTERNAL_SERVER_ERROR, err);
}).then(function () {
var accountName = appSettings.STORAGE_ACCOUNT_NAME;
var accountKey = appSettings.STORAGE_ACCOUNT_ACCESS_KEY;
var host = accountName + '.blob.core.windows.net';
var blobService = azure.createBlobService(accountName, accountKey, host);
return blobService.createContainerIfNotExists("merchant-image", { publicAccessLevel: 'blob' });
}, function (err) {
return response.send(statusCodes.INTERNAL_SERVER_ERROR, err);
}).then(function(error){
if (!error) {
// Provide write access to the container for the next 5 mins.
var sharedAccessPolicy = {
AccessPolicy: {
Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE,
Expiry: new Date(new Date().getTime() + 5 * 60 * 1000)
}
};
// Generate the upload URL with SAS for the new image.
var sasQueryUrl =
blobService.generateSharedAccessSignature("merchant-image",
'', sharedAccessPolicy);
// Set the query string.
returnVal["merchantImage"].sasQueryString = qs.stringify(sasQueryUrl.queryString);
// Set the full path on the new new item,
// which is used for data binding on the client.
returnVal["merchantImage"].imageUri = sasQueryUrl.baseUrl + sasQueryUrl.path + '/'
+ resourceName;
var accountName = appSettings.STORAGE_ACCOUNT_NAME;
var accountKey = appSettings.STORAGE_ACCOUNT_ACCESS_KEY;
var host = accountName + '.blob.core.windows.net';
var blobService = azure.createBlobService(accountName, accountKey, host);
return blobService.createContainerIfNotExists("pharmacy-certificate", { publicAccessLevel: 'blob' });
}
else {
return response.send(statusCodes.INTERNAL_SERVER_ERROR);
}
}, function (err) {
return response.send(statusCodes.INTERNAL_SERVER_ERROR, err);
}).done(function (error) {
if (!error) {
// Provide write access to the container for the next 5 mins.
var sharedAccessPolicy = {
AccessPolicy: {
Permissions: azure.Constants.BlobConstants.SharedAccessPermissions.WRITE,
Expiry: new Date(new Date().getTime() + 5 * 60 * 1000)
}
};
// Generate the upload URL with SAS for the new image.
var sasQueryUrl =
blobService.generateSharedAccessSignature("pharmacy-certificate",
'', sharedAccessPolicy);
// Set the query string.
returnVal["pharmacyCertificate"].sasQueryString = qs.stringify(sasQueryUrl.queryString);
// Set the full path on the new new item,
// which is used for data binding on the client.
returnVal["pharmacyCertificate"].imageUri = sasQueryUrl.baseUrl + sasQueryUrl.path + '/'
+ resourceName;
response.send(statusCodes.OK, returnVal);
}
else {
return response.send(statusCodes.INTERNAL_SERVER_ERROR);
}
}, function (err) {
return response.send(statusCodes.INTERNAL_SERVER_ERROR, err);
});
response.send(statusCodes.OK, { message : 'Hello World!' });
};
exports.get = function(request, response) {
response.send(statusCodes.OK, { message : 'Hello World!' });
};
I am getting following error:
TypeError: Cannot call method 'then' of undefined
at exports.post (D:\home\site\wwwroot\App_Data\config\scripts\api\addWorker.js:17:8)
Azure Mobile Services does not return promises from table operations. You need to pass an options object that contains success and error callbacks, as described at https://msdn.microsoft.com/en-us/library/azure/jj554210.aspx.
I highly recommend that you take a look at the newer implementation of the product, Azure Mobile Apps - https://www.npmjs.com/package/azure-mobile-apps. (Disclaimer: I work for Microsoft on the Azure Mobile Apps team)
I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?