I am beginner in loopback and working on Get Post in loopback
This is code on client side
var datas = 'Something';
$.ajax({
type: 'POST',
url: '/post',
data: datas,
dataType: 'text'
})
.done(function(data) {
console.log('Successful');
.fail(function(jqXhr) {
console.log('Failed');
});
and this is on server side(server.js)
app.post('/post', function(req, res){
console.log('This is DATA '+ req.body);
});
This is not working it gives me 404 not found or failed.
What am I doing wrong and Is there another method for get post in loopback?
the server side needs an server and listening a port.
the client side needs to listen another port.
so they are not in one domain and cannot get access to each other.
this called a "cross-origin requests"
check this for the solution:https://www.w3.org/TR/cors/
Your URL starts with '/'.
Whenever a URL starts with '/' it is treated as absolute URL.
Whereas, most of the time, web apps are bounded with a context root.
Try using URL without initial '/' and it should work.
Related
I am using jQuery Ajax to make a GET request. Sometimes It works perfectly, but other times I get a 403 forbidden when I look at the chrome dev tools console. Is this a server issue or my code?
When I sign in, I get the encrypted password, username and ID back from the server. I then store that in LocalStorage since the request I am trying to get working is on another page. I am also required to make a client token from those fields using AES encryption. For that, I am using CryptoJS. For my request, I am required to send in the password, username, ID and client token that has been retrieved from LocalStorage. I realize that may not be a good way to go about it, but I do not have control of the server side.
Edit: Here is my Ajax call to the service:
$("#system-form").submit(function (e) {
$.ajax({
type: "GET",
url: "myurl",
data: "User.Username=" + localStorage.getItem("guid") + "&User.Password=" + localStorage.getItem("password") + "&User.SecUser=" + localStorage.getItem("secUser") + "&ClientAppID=" + localStorage.getItem("ClientAppId") +"&"+ $(this).serialize(),
})
.done(function(data) {
//parse data
})
.fail(function (xhr, textStatus, error) {
console.log(JSON.stringify(xhr.responseText));
});
e.preventDefault();
});
I realized my issue was that I need to URL encode my auth parameters. I fixed this by using encodeURIComponent.
I am currently learning express, ajax, and nodejs. So currently I am trying to make ajax and nodejs interact with each other. I am sending a client request, using ajax, to a nodejs server. Currently, I am able to invoke app.get in the server correctly, i.e. it works fine until the call to console.log(req.query); at the server side. However, I am having trouble accepting data, that is sent by the server. The client side code does not alert any returned data as I tried to make it to.
This is my code on the client side.
function login(){
var obj = '{"username":"'+$('#username').val()+'", "password":"'+$('#password').val()+'"}';
$.ajax({
type:'GET',
dataType :'json',
data:{"username": $("#username").val(),
"password": $("#password").val()},
url:'http://localhost:10351/function',
success: function (data) {
alert("ajax callaback response:"+JSON.stringify(data));
}
})
This is my code on the server side.
var express = require('express');
var app = express();
var http = require("http");
var server = http.createServer();
var portNumber = 10351;
app.use(express.static('public'));
app.get('/function', function(req, res) {
console.log(req.query);
res.send(JSON.stringify(req.query));
});
app.listen(portNumber, function() {
console.log('Currently listening on port ' + portNumber);
});
Any tips?
I was looking at the answer in the following link:
Node.js, Ajax sending and receiving Json
and I thought maybe i could use response.end and response.setHeader instead?
I'm not quite sure if my problem lies on the client side or the server side.
You don't
Listen to the right port (10901 vs 10351)
Send any parameters in the query section of the url
Need JSON.stringify because you already get a string in (req.query)
You should:
Make the ports match
Send parameters in the url ex:(url:'http://localhost:10351/function?foo=bar)
Remove the stringify ex:
res.send(req.query)
alert("ajax callaback response:"+data);
response.end is not needed if you already use the res.send method, and response.setHeader would be helpful if you want to mark this content as json, so you can put a Content-Type: application/json header,
Or use res.json to do both of these things for you (stringify the json and put the right header for you)
Your ports don't match in code. You said your call worked until console.log(), if the ports don't match it won't even enter app.get() in server.
I think you just posted a different code for client.
I will suggest you to try postman which is chrome extension that will be really helpful to send and get ajax request responses. Using you code just by changing the port number I am able to get the response in postman.
I have a simple API route set up in Express (consumed mainly via my Angular frontend):
app.post('/api/sendEmail', emailApi.sendEmail);
I've made a module that sits in my backend and also needs to call this service. I figured the easiest way was to do a POST request:
request({
url: '/api/sendEmail',
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
});
However, I get this error:
Error: Invalid URI "/api/sendEmail"
What am I doing wrong here?
Change Url to'http://127.0.0.1:3000/api/sendEmail', because you're
calling an internal api with in express or you can also use localhost
in place of 127.0.0.1.
request({
url: 'http://127.0.0.1:3000/api/sendEmail', //on 3000 put your port no.
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function (error, response, body) {
console.log({error: error, response: response, body: body});
});
emailApi.sendEmail is just a function. You are much better off calling it directly. Using the network in this manner would be a serious waste of resources.
On a practical note, there are some complex issues about how to address yourself on the network. Usually you can accomplish this via localhost, but there's no guarantee that the server is listening at that address. So you'll have to take that into account.
You need to use an absolute URI (including the protocol, domain, and port if it's not listening on the default port).
For example, if you know that the server will be listening at localhost:3000, you would want to replace your url value with 'http://localhost:3000/api/sendEmail'.
Assuming you are not using a web server like nginx and are developing on localhost. The express app does not know from where the request has originated. Try setting your Url as http://localhost:300/api/sendEmail.
I have two UIs, one for order.html and one for ledger.html running on two different ports 3000 and 8000 on localhost . On the order page, a user can place an order for an item. Once he places the order, the information is sent as a POST request to server on port 8000.
Below is the post request from the order.html page to server with port 8000
$scope.sendPostRequest=function(){
var dataToBeSent = $scope.postData;
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/receiveOrder',
headers: { 'Content-Type': 'text/plain' },
data: 'some random data'
}).then(function successCallback(response) {
//extracts key:value pairs from the json sent back
$scope.postResponse= someResponse
}, function errorCallback(error) {
// some error handler functions here
})
}
Below is the express code at port 8000 to receive the above request.
app.post('/receiveOrder', function(req, res){
console.log('type of request '+Type(req));
//extract the text passed in data section of the post request
//TODO: Use the data received to update the dashboard, ledger.html
//send some response back as confirmation
});
Once the POST request is received and the data sent is parsed using body-parser, I need to update the UI of ledger.html page to show this.
Basically, ledger.html keeps track of the orders placed by users in real time. It is a dashboard in which fresh orders keep getting added as they are placed. I am stuck in achieving the above.
I have experimented with using socket.io by way of using event-emitters but could not go very far. I have a schema setup for the order data in MongoDB as well in case I need it.
May I have some guidance about what I can use to achieve the above.
This jquery:
$.ajax({
method: "post",
data: JSON.stringify(data),
contentType: "application/json",
url: "http://localhost:3000/ajax"
});
is giving error 404 not found. Here is my server side:
router.get('/ajax', function(req, res ,ext){
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
so i do have the /ajax route. When i go to http://localhost:3000/ajax im able to acccess the site . However, when I try to access it with the ajax method I get the 404 error. So im wondering if the error could be with my code, or if it could be the firewall on my computer. Im actually using a company computer that has a firewall that blocks certain sites and I cannot disable it.
If you want to do a HTTP POST, use router.post, not router.get.
your $.ajax call is using POST but your route in express.js is only listening for GET requests.
When you hit the URL through the browser it's doing a GET, so it worked.
You would need to set up a route for POST with router.post('/ajax', ...)