Im new to node.js. I have server.js , router.js, index.js and requestHandler.js files in my project.
i pass start or upload in url like below
http://localhost:8888/start
I get pathName from url and pass it to router.js in server like below:
server.js :
var http = require("http");
var url = require("url");
function start(route,handle){
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle,pathname);
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
router.js :
function route(handle,pathname){
console.log("About to route a request for "+ pathname );
if(typeof handle[pathname]==='function'){
handle[pathname]();
}else{
console.log("No request handler found for "+pathname);
}
}
exports.route = route ;
index.js :
var server = require("./Server");
var router = require("./router");
var requestHandlers = require("./requestHandler");
var handle={}
handle["/"]=requestHandlers.start;
handle["/start"]=requestHandlers.start;
handle["/upload"]=requestHandlers.upload;
server.start(router.route,handle);
requestHandler.js :
function start(){
console.log("Request handler 'start' was called.");
}
function upload(){
console.log("Request handler 'upload' was called.");
}
exports.start=start;
exports.upload=upload;
I get wrong result :
PS C:\Program Files\nodejs> node ..\..\Users\private\Desktop\hello\index.js
Server has started.
Request for /start received.
About to route a request for /start
No request handler found for undefined
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for undefined
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for undefined
instead of this :
Server has started.
Request for /start received.
About to route a request for /start
Request handler 'start' was called.
what is the problem? any idea?
I tried your code on my machine (Mac OS X + v0.8.9). It works well. The console output is:
Server has started.
Request for /start received.
About to route a request for /start
Request handler 'start' was called.
Request for /favicon.ico received.
About to route a request for /favicon.ico
No request handler found for /favicon.ico
It's tricky why you encountered the error. Can you check you node version?
From the your log data, the problem is in the function route(handle,pathname) defined in router.js. The value of pathname is chanded from "/start" to be undefined. Maybe you need to debug this function to find out the reason.
I encountered this problem also. Seems like I hadn't saved server.js since the last edit.
Related
I have a flask app and I want to send a request with Ajax from my page to another website on the internet( http://hihihi.com/v1/user_likes...for example and this App not flask and I can't change or add any code in the hihihi App).
I set a cookie in my Ajax requests but blocked by the browser. how can I fix this?
Back end flask:
#app.route('/tr')
def test():
return render_template('tr.html')
And in tr.html file as shown as I set header Ajax:
$.ajax({
url: 'http://hihihi.com/api',
type: 'POST',
contentType: 'application/json',headers:{'Cookie' : 'sdfsdfsdfsfdszfvgzzf'}
datatype: 'json',
})
.done(function(data) {
.
.
.
Refused to set unsafe header "Cookie" Error:
In addition, I use this link but not work for me.
Since you are making a same origin request all you need to do is set document.cookie before you make the request.
My setup is running on Docker with a frontend (React) as well as a backend (Django) container.
I'm using the login-form component of the drf-react-app below in another project and am clueless as to how the api fetch request in the loginUser action creator (src/actions/user.js) knows which URL it is supposed to use..?
user.js:22 POST http://localhost:3000/api/obtain-auth-token/ 404 (Not Found)
I want it to send the request to the server at port 8000. I took the code from this drf-react boilerplate: https://github.com/moritz91/drf-react-login
export function loginUser(username, password) {
return (dispatch, getState) => {
const payload = {username, password};
dispatch({type: LOGIN_USER_REQUEST, payload});
return fetch(`/api/obtain-auth-token/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
})
.then(handleResponse(dispatch, LOGIN_USER_RESPONSE))
.then((json) => {
saveUser(json);
return json;
})
.catch(handleError(dispatch, LOGIN_USER_RESPONSE))
}
}
What am I missing?
In your package.json you have a proxy property set to "http://backend:8000". The proxy is used to redirect requests to a given url when you make a request against your local server http://localhost:3000. So if that's not working then you might be missing a step that enables the proxy.
I'm serving an application via AWS Elastic Beanstalk. localhost and ngrok serve the webpage and additional api calls as expected. When uploaded to AWS-ELB a 504 error is the response for any additional api calls after the webpage is served.
The application serves the base index.html file via:
BASIC SETUP AND SERVING INDEX.HTML
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.all('/', ensureSecure)
function ensureSecure(req, res, next){
if(req.headers['x-forwarded-proto'] === 'https'){
// OK, continue
return next()
};
res.redirect('https://' + req.headers.host)
}
app.use(express.static(__dirname + '/../web'), () => {}) // SERVE THE WEBPAGE
var port = process.env.PORT || 443
var router = express.Router()
router.use(function(req, res, next) {
console.log('here')
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next(); // make sure we go to the next routes and don't stop here
});
It then has additional routes below it:
SUBSEQUENT API CALL
app.get('/user/:type', function(req, res) {
res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
var dbparams = {};
dbparams.TableName = 'FFUserTable';
dbparams.KeyConditionExpression = 'uid = :uid'
dbparams.ExpressionAttributeValues = {':uid':req.query.uid};
ddb_calls.awsDynamoQuery(dbparams, function(data){
res.json(data);
})
})
The index page serves and renders just fine. But any of the routes below it return a 504 gateway error when the page makes calls to them. The strange thing is that this only happens when deployed to AWS-ELB. Everything works as expected when using localhost or when using ngrok. Even if I take out the https redirect I get the same issue.
AWS-ELB ssl is setup and routed correctly via AWS-Route53.
This is the problem:
app.use(express.static(__dirname + '/../web'), () => {})
I'm not sure why you added that last function there, but it's an (incomplete) middleware function that will stall all requests because it's not doing anything.
It should be this:
app.use(express.static(__dirname + '/../web'))
I use Stripe in an Ember app. Stripe makes request to this address : https://checkout.stripe.com/api/outer/manhattan?key=... In my acceptance test, I have this message : Pretender intercepted GET https://checkout.stripe.com/api/outer/manhattan?key=... but no handler was defined for this type of request.
I tried to stub this request like this :
var server = new Pretender(function() {
this.get("/api/outer/manhattan", function() {
return [200, {}, this.passthrough];
});
});
But it does not work. I also tried with the full url or with a wildcard without success.
Is there a solution ?
I have created a page on locahost:8080/kar, i am sending an ajax POST request to different Url(same domain) i.e. locahost:8080/kar/create_post there i am returning an HTML response but its not showing on the browser as the URL is still on locahost:8080/kar, the data is stored in the database.Where as in the developer console i can see the response in the network tab .When i redirect it is also showing the same thing in the developer console
Why i am not able to change the URl and see the response ?
It's a client side thing, that means the desired behaviour needs to be implemented with javascript. Django is functioning normally here.
When you're sending Requests via AJAX, that is a non blocking request with the XMLHttpRequestheader set, your browser won't trigger the chain of events that occurs when a server side script evaluates your form and returns something, which may be data, or a redirect, depending on whether the form validated or not.
A typical AJAX call in jQuery looks like this:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
If you would like to perform some actions when the request you sent by XMLHttpRequest returns, you could attach that to the appropriate success handler:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
If you need to redirect to the URI that is returned as a redirect from your server you can get the redirect URI from the response in the success handler:
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
If you would like to modify the URL in the users bar without reloading the page you could have a look at this question.