I am trying to create an API using a local server for testing. The ROUTES are working and I can add data to the OBJ using the URL from the browser. The issue is when I try to 'POST' the data through the HTML. I am getting back a 404 error. I developing using node.js and Express. What am I doing wrong?
JS on the server side
app.get('/add/:word/:score?', addWord);
//Function to request and send back the data
function addWord(request, response) {
var data = request.params;
var word = data.word;
var score = Number(data.score);
var reply;
if (!score) {
var reply = {
msg: 'Score is required'
}
response.send(reply);
} else {
words[word] = score;
// Transforms javascript object into raw data correctly idented with null, 2
var data = JSON.stringify(words, null, 2);
fs.writeFile('words.json', data, finished);
function finished(err) {
console.log('Writting');
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
}
POST method JS
$('#submit').on('click', function submitWord() {
var word = $('#fieldWord').val();
var score = $('#fieldScore').val();
$.ajax({
type: 'POST',
url: '/add/' + word + "/" + score,
success: function (newOrder) {
$list.append('<li>name: ' + newOrder.word + newOrder.score + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tutorial API with node.js</title>
<script type="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>
Word: <input type="text" id="fieldWord"><br/>
Score:<input type="text" id="fieldScore"><br/>
<button type="button" id ="submit">Submit</button>
<ul id="list">
</ul>
</p>
</body>
<script type="text/javascript" src="sketch.js"></script>
</html>
Thank you in advance.
Related
I have arduino esp32 which i have sent data over mqtt to my cloudmqtt broker.
What it is sending is real time random numbers.
I can view these numbers on the cloudmqtt broker but i want it to be transferred to my webpage, so i researched and found some information on websockets.
This is the code i have currently:
<html>
<head>
<title>JavaScript MQTT WebSocket Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var mqtt;
var reconnectTimeout = 2000;
var host = "farmer.cloudmqtt.com"; //change this
var port = 37511;
var user = "foo";
var pass = "bar";
function MQTTconnect() {
console.log("connecting to " + host + " " + port);
mqtt = new Paho.MQTT.Client("farmer.cloudmqtt.com", 37511, "web_" + parseInt(Math.random() * 100, 10));
mqtt.onMessageArrived = onMessageArrived;
//document.write("connecting to "+ host);
var options = {
useSSL: true,
userName: "foo",
password: "bar",
onSuccess: onConnect,
onFailure: doFail
};
mqtt.connect(options); //connect
};
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("Connected ");
//mqtt.subscribe("sensor1");
message = new Paho.MQTT.Message("Hello world");
message.destinationName = "esp/test";
mqtt.send(message);
}
function doFail(e) {
console.log(e);
}
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
</script>
</head>
<body>
<h1>Main Body</h1>
<script>
MQTTconnect();
</script>
</body>
</html>
But when i view my conosle it doesnt seem to work and gives error:
HTML1300: Navigation occurred.
webpage.html (1,1)
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: “”.
webpage.html (1,1)
connecting to farmer.cloudmqtt.com 37511
webpage.html (14,13)
0: Unspecified error.
mqttws31.min.js (28,16)
I am not sure why i get this error i dont see any errors in my code.
I would like to design Javascript web application. In that application, I need to show reports dashboard like daily sales report, the data to be fetched from odoo application.
So I used odoo-xmlrpc to connect javascript to odoo.
js.file
var Promise = require('promise');
var async = require("async");
var Odoo = require('odoo-xmlrpc');
var odoo = new Odoo({
url: 'localhost',
port: '8063',
db: 'db_1',
username: 'admin',
password: '123'
});
function color(){
return new Promise(resolve => {
odoo.connect(function (err) {
if (err) { return console.log(err); }
console.log('Connected to Odoo server.');
var inParams = [];
inParams.push([[],[]]);
var params = [];
params.push(inParams);
odoo.execute_kw('account.invoice', 'check_func', [[[], []]], function (err, value) {
if (err) { return console.log(err); }
console.log('Result: ', value); //Result: Done
resolve(value);
});
});
});
}
async function changeColor(newColor) {
//document.getElementById("para").innerHTML = "Hello3"; //this line working
var result = await color();
console.log(result, "###########")// Result Done
var elem = document.getElementById('para').innerHTML="tet"; //This line dot working
}
changeColor('red')
check_func() in python
#api.multi
def check_func(self):
return "done"
html file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="/home/priya/Desktop/ra.js"></script>
</head>
<body>
<h2 style="text-align:center;">Reports</h2>
<div style="text-align:center;">
<input type="button" onclick="sales_report_retail()" value="Sales report"/>
<p id="para"></p>
</div>
</body>
</html>
In that odoo.execute_kw(), I used resolve(value). That value is working with in odoo.execute_kw().
var result = await sales_report_retail_db(); this line value gets correctly but after this line document.getelementbyid is not working.
I need to show that value in web page. So how to correct this?
I am trying to build a web application which is supposed to use Microsoft Azures Cognitve Services Emotion API.
I use JavaScript (jQuery) to send a AJAX-request to my assigned endpoint-server.
This is my attempt:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<h2>Face Rectangle</h2>
<ul id="faceRectangle">
</ul>
<h2>Emotions</h2>
<ul id="scores">
</ul>
<body>
<script type="text/javascript">
$(function() {
var params = { };
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/emotion/v1.0?" + $.param(params),
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","<key>");
},
type: "POST",
data: '{"url": "<some picture's URL>"}',
}).done(function(data) {
var faceRectangle = data[0].faceRectangle;
var faceRectangleList = $('#faceRectangle');
for (var prop in faceRectangle) {
faceRectangleList.append("<li> " + prop + ": " + faceRectangle[prop] + "</li>");
}
var scores = data[0].scores;
var scoresList = $('#scores');
for(var prop in scores) {
scoresList.append("<li> " + prop + ": " + scores[prop] + "</li>")
}
}).fail(function(err) {
alert("Error: " + JSON.stringify(err));
});
});
</script>
</body>
</html>
The exact error response from the server is:
Error: {"readyState":4,"responseText":"{ \"error\": { \"code\": \"ResourceNotFound\", \"message\": \"resource not found.\" } }","status":404,"statusText":"Resource Not Found"}
obviously the server cannot answer my request. Can somebody interpret the server's error response or see a flaw in my code?
Based on the official documentation, the request URL of Emotion API should be:
https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize
I am trying to search a local Solr core and am getting no response using getJSON. I know the URL works and returns a response but the getJson function seems to return null.
<!DOCTYPE html>
<html>
<head>
<title>Ray Search</title>
</head>
<body>
Document ID:<br>
<input id="query" type="text" name="document_ID"><br>
<button onclick="searchSolr();">Search</button>
<div id="results">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
function searchSolr() {
var searchStr = $('#query').val();
if (searchStr.length == 0) {
return;
}
var searchURL = "http://localhost:8983/solr/Ray-Docs/select?q=*&wt=json&json.wrf=on_data";
$.getJSON(searchURL, function (result) {
var docs = result.response.docs;
var total = 'Found ' + result.response.numFound + ' results';
$('#results').prepend('<div>' + total + '</div>');
});
}
</script>
</html>
Did you try invoking getJSON like below?
jQuery.getJSON(sourceURL).done(function(returnData){
//Data Processing
});
I'm working on a simple website and I'm having a problem when sending a JSON to the API. The JSON will be received as EMPTY if is sent using the html/js, but when using postman everything works as expected.
The structure of files is simply the server running on node.js, an html page with his javascript to build the JSON and send it.
The html file code as it follows :
<!DOCTYPE html>
<html lang="en">
<head>
<body>
</head>
Receiver Address
<input type="text" placeholder="Write the target address..." id="target_address"></input><br>
Message
<input type="text" placeholder="Write the message in plain text..." id="message"></input><br>
<input type="submit" value="Send" id="accept"></input>
<br>
<div id="results"><div>
</body>
<script src="js/jquery.js"></script>
<script src="js/main.js"></script>
</html>
The javascript file is :
var URL_API = "http://localhost:3000/nr";
$("#accept").click(function(e) {
e.preventDefault();
var url = URL_API;
var object = new Object();
object.L = 1;
object.B = ($("#target_address").val());
object.message =($("#message").val());
object.po = "ProofofOrigin";
var data = JSON.stringify(object);
console.log(data);
$.ajax({
url : url,
type : 'POST',
crossDomain : true,
dataType : 'json',
contentType : 'application',
data : data,
dataType:'json',
}).done(function(data, status, jqxhr) {
window.alert("Information sent successfully");
console.log(data.B);
}).fail(function(data) {
window.alert("ERROR");
});
});
Then the part of node which is executing when receiving the given POST :
router.post('/', function(req, res, next) {
var updateStep = Number(req.body.L)+1;
var ProofofOrigin = req.body.message + "Message signed - POO";
var info_JSON = {
address: req.body.B,
step: updateStep,
message: req.body.message,
po: req.body.po,
};
JSON.stringify(info_JSON);
//res.send("Address : " + req.body.B + " \nStep : " + req.body.L + " \nMessage : " + req.body.C + " \nPOO : " + req.body.Po);
res.send(info_JSON);
//console.log(info_JSON);
});
For some reason the req.body (where the JSON should be saved) is completely empty on the body, but if I send it using Postman it will work.
I don't know what could be wrong.
Please verify this:
In javascript (client side):
contentType : 'application/json',
In nodejs (server side):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/api/doSomething', function(req, res) {
var mydata = req.body.mydata;
...
return res.json({result: result});
});
You need to include the body parser module to be able to parse JSON bodies.