Between express server and react.js - fetch does not work? - ajax

I am trying to get data in react by sending GET or POST request to express server.
But I can't receive response from server.
Below is my React component code.
handleButton() {
const sendData = {
"say" : "Hello",
"to" : "React App"
};
fetch("http://localhost:5000/", {
mode : "no-cors",
method : "POST",
body : JSON.stringify(sendData)
}).then(res => {
console.log(res);
alert(res);
});
}
handleButton() is called when I press the button.
I want to receive data from server when I click the button.
Then here is my express server code.
var express = require("express");
var bodyParser = require("body-parser");
var multer = require("multer");
var upload = multer();
var app = express();
app.get("/", function(req, res) {
res.render("form");
});
app.set("view engine", "pug");
app.set("views", "./views");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended : true}));
app.use(upload.array());
app.use(express.static("public"));
app.post("/", function(req, res) {
console.log(req.body);
res.send("received your request!");
});
app.listen(5000);
My server is very simple but it doesn't work.
When I press the button, server console outputs empty object.
This is my server console capture image.
And then this is my google chrome browser console capture image.
Please help me with getting right result. I want to notice that server received request by alert in react.

Related

How to get each http body updates on angular Http request?

I'm using an express api (my back-end) and an angular app (my front-end).
One express js end point (let's call it '/foo') is processing a lot of files,
i send data using res.write() after each treatment so the http response body is update.
I would like to get this update on my angular app.
I was using ajax in a previous version and it worked fine with ajax call :
xhrFields: {
// Getting on progress streaming response
onprogress: function(e)
{
var progressResponse;
var response = e.currentTarget.response;
if(lastResponseLength === false)
{
progressResponse = response;
lastResponseLength = response.length;
}
else
{
progressResponse = response.substring(lastResponseLength);
lastResponseLength = response.length;
}
actualResponse += progressResponse
}
Unfortunatly i found nothing to get partial http body. I tried to use 'reportProgress' Parameter but it's not working.
For some more context my front-end angular code:
service.ts :
setHolidaysDirectory(holidaysKey: string, path: string): Observable<Object>{
const setHolidayDirectoryStreamHttpRequest =
new HttpRequest('POST', 'http://localhost:8089/holidays/pictures/edit', { 'key': holidaysKey,
'path': path
}, {headers: this._httpHeaders, reportProgress: true, responseType: 'text'});
// pipe stream answer
return this._http.request(setHolidayDirectoryStreamHttpRequest);
}
and my component just call the service and subscribe :
this._holidaysService
.setHolidaysDirectory(key, finalHolidaysForm.path)
.subscribe((stream) => {
console.log('new answer');
console.log(stream);
}, error => console.log(error));
But unfortunatly i got empty answer and all the http body is recovered after res.end() (server side)
Can anyone help pls !
Thank a lot !

InAppBrowser close() freeze UI

My application is using Ionic 2. When a user launches, they are met by the splashscreen. After a few seconds an instance of InAppBrowser launches for them to login to a company portal. Once the browser is redirected, the browsers listens for the 'loaderror'. At which point the browser closes, and Splashscreen.hide() is used. 9 times out of 10, the UI is frozen and the user tap or touch anything on the screen. If I put a done button to close the browser manually, 5 times out of 10 the UI freezes. My code is below:
public freshPOST() {
//declare ESO login page as well as open Inappbrowser
var url_code: any;
let url = "CLIENT_AUTH_ENDPOINT_URL";
let browser = new InAppBrowser(url, '_blank', 'location=no,zoom=yes,enableViewportScale=yes,toolbar=no');
//on redirect browser shows load error, and not url
browser.on("loaderror").subscribe((event: InAppBrowserEvent) => {
//pull code from url and store in variable
let token = event.url.split('=')[1].split('&')[0];
url_code = token;
localStorage.setItem('url_code', url_code);
//SETUP FOR POST
//headers to be sent
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
//parameters for POST request
let details = "code=" + url_code + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=REDIRECT_URI&grant_type=authorization_code";
//POST request with parameters injected
this.http.post('CLIENT_TOKEN_ENDPOINT', details, options)
.map(res => res.json())
.subscribe(
data => {
//convert response to string, pull access token, and store in variable
this.data = JSON.stringify(data)
var access_token = data.access_token;
var expires_in = data.expires_in;
var refresh_token = data.refresh_token;
//store all responses to local storage for retrieval
localStorage.setItem('access_token', access_token);
localStorage.setItem('expires_in', expires_in);
localStorage.setItem('refresh_token', refresh_token);
//launch app
//write to console success
//close browser
console.log("Successful POST and Authentication");
browser.close();
Splashscreen.hide();
},
(err) => {
//POST Failure
//close browser
console.log("post didnt work");
});
});
}
I am launching this from App.Component, and only if platform is ready. The first page is an intro page that you skip to get to the tabbed view. Thank you for any help you can provide.

failed to load source: unsupported URL when trying a post request

I'm trying to use a simple post request on a route on top of a mongo DB.
my js file (I combined the router with the app) looks like:
var express = require('express');
var app = express();
var router = express.Router();
app.use(express.static('public'));
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server;
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
//Close connection
//db.close();
}});
router.post('/', function(req, res){
res.send('Got a POST request');
});
app.listen(27017,function(){
console.log("Server started successfully at Port 27017!");
});
on my html file I simple have a section like this (yes, my post request doesn't do much for now):
$.ajax({
method: "POST",
url: "localhost:27017/test/",
});
I can't seem to get it to work, my console keeps throwing: "[Error] Failed to load resource: unsupported URL (localhost:27017/test/, line 0)"
at me, and when I try to browse directly to the url via my browser I'm getting a "Cannot GET /test/" message.
What am I doing wrong?
Sharing what worked for me in the end:
1. Changed the app to listen to 3000 (or any other port that my DB server wasn't listening to). Thanks TomG.
2.changed router.post to app.post (you can use expressing routing but I had a mistake there).

Cloud Code Parse.User.current() return null

When i use this function in Cloud Code Parse.User.current() return null.
I'm using parseExpressCookieSession for login.
Any advice?
var express = require('express');
var expressLayouts = require('cloud/express-layouts');
var parseExpressHttpsRedirect = require('parse-express-https-redirect');
var parseExpressCookieSession = require('parse-express-cookie-session');
// Required for initializing enter code hereExpress app in Cloud Code.
var app = express();
// Global app configuration section
app.set('views', 'cloud/views');
app.set('view engine', 'ejs'); // Switch to Jade by replacing ejs with jade here.
app.use(expressLayouts); // Use the layout engine for express
app.set('layout', 'layout');
app.use(parseExpressHttpsRedirect()); // Require user to be on HTTPS.
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('helloworld'));
app.use(parseExpressCookieSession({
fetchUser: true,
cookie: { maxAge: 3600000 * 24 }
}));
Parse.Cloud.beforeSave('Menu', function(request, response) {
var Business = Parse.Object.extend('Business');
var query = new Parse.Query(Business);
query.equalTo('profile', Parse.User.current().get('profile'));
query.find({
success: function(business) {
console.log(business);
response.success();
},
error: function(error) {
response.error(error.message);
}
});
});
app.listen();
This the code that i use to login/logout
app.post('/login', function(req, res) {
Parse.User.logIn(req.body.username, req.body.password).then(function(user) {
// Login succeeded, redirect to homepage.
// parseExpressCookieSession will automatically set cookie.
res.redirect('/');
},
function(error) {
// Login failed, redirect back to login form.
res.redirect('/');
});
});
// Logs out the user
app.post('/logout', function(req, res) {
Parse.User.logOut();
res.redirect('/');
});
It is an old question but answering for future reference.
Parse.User.current() works in Javascript SDK when used in clients ex. WebApp where users log in and the you can fetch the current user with that function.
To get the user calling a Cloud Code function or doing an operation on an object (beforeSave,afterSave,beforeDelete and so on) you use the request.user property it contains the user issuing the request to Parse.com.
More details about Parse.Cloud.FunctionRequest here: https://parse.com/docs/js/api/classes/Parse.Cloud.FunctionRequest.html
Example code:
Parse.Cloud.beforeSave('Menu', function(request, response) {
var requestUser = request.user;
// instance of Parse.User object of the user calling .save() on an object of class "Menu"
// code cut for brevity
});

How to send data from server to client via http?

I want to send the filepath of a file on my server to the client in order to play it using a media player. How can I retrieve that string on the client side in order to concatenate it in the src attribute of a <video element without using sockets?
Server snippet:
res.set('content-type', 'text/plain');
res.send('/files/download.mp4');
This is how you make a request to the server without any frameworks. "/path_to_page" is the route you set to the page that is supposed to process the request.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path_to_page', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText); // output will be "/files/download.mp4"
}
};
xhr.send();
}
You might also want to send some params.
var formdata = new FormData();
formdata.append("param_name", "value");
So you might for instance want to send the filename or such.
You just need to change 2 lines from the first code snippet. One would be
xhr.open('POST', '/path_to_page', true); // set to post to send the params
xhr.send(formdata); // send the params
To get the params on the server, if you are using express, they are in req.body.param_name
Which framework are you using??
You can declare base path of your project directory in ajax and the followed by your file.
jQuery.ajax({
type: "GET",
url: "/files/download.mp4",
});
Since you are using express (on node), you could use socket.io:
Server:
var io = require('socket.io').listen(80),
fs = require('fs');
io.sockets.on('connection', function (socket) {
socket.on('download', function(req) {
fs.readFile(req.path, function (err, data) {
if (err) throw err;
socket.emit('video', { video: data });
});
});
});
Client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
...
// request a download
socket.emit('download', { path: '/files/download.mp4' });
// receive a download
socket.on('video', function (data) {
// do sth with data.video;
});
...
</script>
Edit: didnt notice you didnt want to use sockets. Still it is a viable solution.

Resources