so I'm posting this question after a hours of research .... That's the answer of the browser and I can't find any reason why...
So, after the login, I want to fetch the score of the user logged. The score is located in a subtable of the user table (Mongo ...). But the call for the server doesn't work. Here is my code :
login.component.ts
this.dbService.scoresDownload(this.username).subscribe(scoresDownload => {
console.log(scoresDownload);
});
db.service.ts
scoresDownload(username) {
this.createAuthenticationHeaders();
console.log(username)
return this.http.post(this.domain + 'training/scoresDownload', username, this.options).map(res => res.json());
}
training.js (route in Express)
router.post('/scoresDownload', (req, res) => {
// let wordScoresDb = [];
console.log(req)
User.find({}, (err, result) => {
if (err) {
res.json({ success: false, message: err }); // Return connection error
} else {
res.json({ success: true, message: result }); // Return as vailable username
}
})});
It works well if I use a get instead of a post .... And the most tricky part is that it works with all my other calls. So, I really don't know where I mess up ...
Cheers guys !
EDIT :
I forgot to mention the error sent by express
SyntaxError: Unexpected token # in JSON at position 0
at Object.parse (native)
at createStrictSyntaxError (D:\Code\Deutsch_App_MEAN\node_modules\body-parser\lib\types\json.js:157:10)
at parse (D:\Code\Deutsch_App_MEAN\node_modules\body-parser\lib\types\json.js:83:15)
at D:\Code\Deutsch_App_MEAN\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (D:\Code\Deutsch_App_MEAN\node_modules\raw-body\index.js:224:16)
at done (D:\Code\Deutsch_App_MEAN\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (D:\Code\Deutsch_App_MEAN\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Ok ... I miserably found the answer ... the username I was passing through MEAN is a string ... Apparently the "post" from the http module does accept only object or array, and not string ... VoilĂ :)
Related
I want to send an array of strings over localhost 3000 with route start then send back a response with status 200 and eventually a map attached to response.body Currently i have this
Client code:
const axios = require('axios');
let listOfNames = ['mikey'];
axios.post(''http://localhost:3000/start'', {
data: { names: listOfNames }
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Server code:
const express = require('express');
const app = express()
const port = 3000
var listOfNames = [];
app.post('/start', async (req, res) => {
listOfNames = req.params.listOfNames;
res.status(200).send("Names added");
});
app.listen(port, () => {
console.log('request recieved');
});
I get this error presemably from how the request is being sent, any help?
TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:393:5)
at URL.onParseError (node:internal/url:565:9)
at new URL (node:internal/url:645:5)
at dispatchHttpRequest (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:23
94:20)
at new Promise (<anonymous>)
at http (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:2330:10)
at Axios.dispatchRequest (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:
3260:10)
at Axios.request (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:3610:33)
at Axios.httpMethod [as post] (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios
.cjs:3649:19)
at Function.wrap [as post] (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cj
s:27:15) {
input: '/start',
code: 'ERR_INVALID_URL'
}
Edit: New error ECONNRESET error emerging from applied fixes
AxiosError: read ECONNRESET
at AxiosError.from (C:\Users\cmb\rectangleHealth\node_modules\axios\dist\node\axios.cjs:789:14
)
at RedirectableRequest.handleRequestError (C:\Users\cmb\rectangleHealth\node_modules\axios\dis
t\node\axios.cjs:2744:25)
at RedirectableRequest.emit (node:events:513:28)
at eventHandlers.<computed> (C:\Users\cmb\rectangleHealth\node_modules\follow-redirects\index.
js:14:24)
at ClientRequest.emit (node:events:513:28)
at Socket.socketErrorListener (node:_http_client:494:9)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
syscall: 'read',
code: 'ECONNRESET',
errno: -4077,
The console also outputs a 2 json objects called request and config that cannot fit into this post.
I noticed 2 things errors in your code:
First, check your url is correct, instead of
''http://localhost:3000/start'' (you have multiple single quotes wrapping the url)
try,
"http://localhost:3000/start" or 'http://localhost:3000/start' (wrap it in proper double quotes or single quotes)
Second, You are passing the data in your api call as request body and not as request parameters, but you are trying to access it in the parameters of your api.
You should try accessing the request's body on the server side instead of parameters,
app.post('/start', async (req, res) => {
listOfNames = req.body.listOfNames;
res.status(200).send("Names added");
});
Else you might probably face issue while accessing the data in api as well.
I am trying to create a route so that when someone accesses it, it will download a file and send a response message to the user (should appear in the HTML). I am using the download function from express JS but it failed.
This is my code:
router.get('/api/zip', AuthMiddleware, (req, res) => {
//console.log("hello");
//return res.status(200).download(".\\views\\index.zip"); => download but doesn't send message to the user.
res.download(".\\views\\index.zip", "index.zip", (err) => {
if (err) {
res.status(500).send({
message: "Could not download the file. " + err,
});
} else {
try {
res.status(200).send("Download!");
} catch (error) {
res.status(500).send("Download fail 2");
}
}
});
});
After the user access http://localhost:4000/api/zip, it downloads the file and the server crashes:
[nodemon] starting `node index.js`
Listening on port 4000
_http_outgoing.js:561
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (internal/errors.js:322:7)
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (D:\MyProject\node_modules\express\lib\response.js:794:10)
at ServerResponse.send (D:\MyProject\node_modules\express\lib\response.js:174:12)
at D:\MyProject\routes\index.js:34:21
at D:\MyProject\node_modules\express\lib\response.js:450:22
at SendStream.onend (D:\MyProject\node_modules\express\lib\response.js:1078:5)
at SendStream.emit (events.js:400:28)
at ReadStream.onend (D:\MyProject\node_modules\send\index.js:813:10)
at ReadStream.emit (events.js:412:35) {
code: 'ERR_HTTP_HEADERS_SENT'
I understand that I can't use download and then send, so how can I download and send message to the user on the HTML page?
You already know that you can't send 2 responses one after the other.
What can be done, is setting a custom header for your response, so something like this:
app.get('/download', (req, res) => {
res.append('message', JSON.stringify({ message : "hello"}) );
res.download("test.txt", "try.txt");
});
And then get the message from that, It feels really "hacky" though...
I use supertest to test web API, and I created a function to get the token,
module.exports.getToken = () => {
let query =
{
"email": config.dev.adminUsername,
"password": config.dev.adminPassword,
"applicationId": config.dev.applicationId
}
request(config.dev.loginUrl)
.post('/login')
.send(query)
.expect(200)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
}
but I got error looks like,
{ SyntaxError: Unexpected token e in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.res.on (C:\WorkSpace\Postman\saasify-integration-tests\supertest_testScripts\node_modules\superagent\lib\node\parsers\json.js:11:35)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
rawResponse: 'eyJraWQiOiJ4eGh5cXV3.................FRfeCpAm3sYxY7fV-WDK1w',
statusCode: 200,
response: undefined }
But same request and url in postman I can get the token string without error. what I did wrong?
I have an web app with using Twitter API. Main focus is to get the users that are not following back based on given twitter user name. It works fine until this point but when I get an error because of the fact that user name does not exist on Twitter, Server shuts down itself. Using Nodejs, expressjs.
The Error Message :
App is running on port : 3000
[ { code: 34, message: 'Sorry, that page does not exist.' } ]
_http_outgoing.js:494
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:767:10)
at ServerResponse.send (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/express/lib/response.js:170:12)
at /home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/twitter-api.js:30:21
at Request._callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/twitter/lib/twitter.js:215:14)
at Request.self.callback (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:186:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/home/ugurcan/dev/Projects/Twitter-App/twitter-api-app/node_modules/request/request.js:1163:10)
Problematic part of the code is below. The question is : How can I avoid this situation ? Or is it even possible ?
client.get('followers/ids', params, function(error, followers_results, response) {
if (error) {
res.send("error");
console.log(error);
}
let followers = followers_results.ids;
client.get('friends/ids', params, function(error, following_results, response ) {
if (error) {
res.send("error");
console.log(error);
}
let following = following_results.ids;
following.forEach(function(person){
if(followers.indexOf(person) === -1){
one_way_following.push(person);
}
});
// console.log(one_way_following);
one_way_following = one_way_following.slice(0, 100);
one_way_following_string = one_way_following.join();
// console.log("----------------------------------------------------");
// console.log(one_way_following_string);
// console.log("----------------------------------------------------");
client.get('users/lookup', {user_id: one_way_following_string}, function(error, user_results, response, next) {
if (error) {
res.send("error");
console.log(error);
}
user_results.forEach(function(user){
let userObject = {
name : user.name,
screen_name : user.screen_name,
avatar: user.profile_image_url
}
// console.log(user.name);
users.push(userObject);
})
res.render("results.ejs",{users:users});
// console.log(users);
});
});
});
This error is actually happening because, you can't call res.render("results.ejs",{users:users}); or res.send("error"); multiple times, because headers can't be changed once set.
Easiest solution would be to break out of the function once you've caught an error (if (error) { on line 2), or handle it appropriately (render something blank, or render your friendly error view).
For more information, about this, check out the answer to this question, Error: Can't set headers after they are sent to the client
Hope that helps :)
After a http response, I am sending a messing using RabbitMQ (creating a channel etc) and however, the server is complaining that "Error: Can't set headers after they are sent."
Here is the code:
var amqp = require('amqplib');
var when = require('when');
var rabbitmq_conn = amqp.connect('amqp://localhost' );
function push_keystroke_data(session_id, data) {
var QUEUE_NAME = 'hello';
var msg = session_id;
when(rabbitmq_conn.createChannel()).then(function(ch) {
var ok = ch.assertQueue(QUEUE_NAME, {durable: false});
ok.then(function(_qok) {
ch.sendToQueue(QUEUE_NAME, new Buffer(msg));
console.log(" [x] Sent '%s'", msg);
ch.close();
});
}).ensure(function() {
conn.close();
});
}
router.post('/', function(req, res, next) {
// current session id
var sid;
if (req.cookies.papi) {
sid = req.cookies.papi.session_id;
} else {
sid = generate_session_id();
res.cookie('papi', {session_id: sid}, {maxAge: COOKIE_MAX_AGE});
}
res.send(JSON.stringify({ user_id: get_user_id(sid)}));
var data = process_keystroke_data(req.body);
push_keystroke_data(sid, data);
});
I assuming RabbitMQ is setting the headers after the response (I have also tried sending the RabbitMQ message before the response but that also didn't solve anything).
Here is the stack trace:
POST /api 500 220.100 ms - 16
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:700:10)
at ServerResponse.send (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:154:12)
at fn (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:934:10)
at View.exports.renderFile [as engine] (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/jade/lib/index.js:374:12)
at View.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/view.js:93:8)
at EventEmitter.app.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/application.js:566:10)
at ServerResponse.res.render (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/response.js:938:7)
at /Users/mikeecb/Documents/KeyNA/jsbackend/app.js:62:7
at Layer.handle_error (/Users/mikeecb/Documents/KeyNA/jsbackend/node_modules/express/lib/router/layer.js:58:5)
Any solutions or ideas would be much appreciated.
It turns out that the issue was not that RabbitMQ was setting the headers (which would be weird, why would it be doing any http stuff?) but that after responding res.send(JSON.stringify({ user_id: get_user_id(sid)}));, I tried to send another respond which obviously the issue.