Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 days ago.
Improve this question
I am making a quiz website and I need the quiz.ejs to send the inputted values to the server. I want the quiz to display a sentence and the user to selected true or false (about 20 questions). I used JavaScript to change the displayed sentence and to store the answer. Is there away to send the stored answers to the server?
I know the "form" element exists, but since I use the same "true" and "false" check-boxes for all questions I can't just send the value. Do I have to make a new checkbox for each question or can I send the data from the JavaScript file.
Thank you so much in advance.
I don't know what to try.
You will need to do an ajax post, from the clientside
Either a standard html form post, or use a javascript library like axios, fetch or even jquery
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
You will need to receive the ajax post, from the server
This is handled in your node server.
const app = express()
// other stuff...
// Handle post to /user
app.post('/user', (req, res) => {
// handle request stuff here...
// return json etc optional.
// res.json({})
})
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How to sent post request to mLab Database to check if user have already account or not Server Response User is not Define. Check my code
// #route post api/user/login#
router.post('/login',(req,resp)=>{
const email=req.body.email;
const password=req.body.password;
// find user
user.findOne({email})
.then(user => {
if(!user){
return resp.status(404).json({email: "User not found "})
}
// check password
bcrypt.compare(password,user.password)
.then(isMatch=>{
if(isMatch){
resp.json({msg:'sucess'})
}else{
return resp.status(400).json({password:'password incorrect'});
}});
});
});
Post Request to Server
http://localhost:5000/api/users/login
Key Value
email MyEmail#gmail.com
Password MyPassword
Response from Server
ReferenceError: user is not defined
user.findOne({email}) should be User.findOne({email}). user with a capital U
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I`m new at node
I use node as a back end server with mongodb
and call it using a android device
my case is I set timeout from android to post a request in node, then from android it just return timeout because it wait too long.. but after several seconds the data is created at mongodb because if internet is so slow so it takes several seconds, I just cut the connection in android and cant cut it at node.
anyone can help what is the best practice to using timeout in android? let say I set timeout to 60sec, if the request longer than 10 sec I want to cut the connection because it takes too long
thanks anyway :))
Try this
exports.testInsert = function(req, res){
testModel.update({user_id: req.body.user_id}, {$set: {username: 'test'}},{upsert: true, setDefaultsOnInsert: true})
.lean()
.exec(function(err, data){
if (err) {
res.send({ err_num: 100000, err_str: err });
return false
}
res.send({ err_num: 0, err_str: 'Success' })
})
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to do a POST action with node.js with a command line application.
The goal is to login to http://hbeta.net
(I want to create a application that post the username and the password automaticly)
thanks ;)
If the website supports posting data to the login and receiving a login cookie/token back, you can use the following code:
var cloudscraper = require('cloudscraper');
cloudscraper.post('http://hbeta.net/', {
username: 'username',
password: 'password'
}, function(error, response, body) {
if (error) {
console.log("an error has occured");
} else {
console.log(body, response);
}
});
This code will simply send a POST method to http://hbeta.net/ while bypassing their CloudFlare DDOS protection and send a username and password along with the request.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Nodejs server side implementation: How to use https://www.npmjs.com/package/request with https://www.npmjs.com/package/rx to make GET request to https://www.reddit.com/r/javascript.json?
Goal: I attempting to accomplish constant streaming whenever there are data changes to whatever site api url I'm using.
Unfortunately you will be unable to receive updates when https://www.reddit.com/r/javascript.json is updated as there is no way for them to push this information to the client.
Services such as Github will let you register a webhook which will let them push data to an endpoint on your server. I am unsure if Reddit supports this.
As an alternate solution, and building on what AkkarinZA said in his answer, you could poll the json document using something similar to the following:
var fetchContent = function(url) {
return rx.Observable.create(function (observer) {
request(url, function (error, response, body) {
if (error) { observer.onError(); }
else { observer.onNext({response: response, body: body }); }
observer.onCompleted();
})
});
};
rx.Observable.interval(1000)
.map(function() { return 'https://www.reddit.com/r/javascript.json' })
.flatMap(fetchContent)
.map(/* do something */)
.subscribe();
Polling such as this isn't a good approach.
You want to create an observable with observers notified from the callback. Try something like:
rx.Observable.create(function (observer) {
request('https://www.reddit.com/r/javascript.json', function (error, response, body) {
if (error) { observer.onError(); }
else { observer.onNext({response: response, body: body }); }
observer.onCompleted();
})
})
.map(/* do something */)
.subscribe();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm actually creating an application and I need to make some integration tests.
I'm actually wondering how should I do to avoid the real behaviour of my express call back routes.
Example: admitting that I want to post a data on an express route and check that I get a HTTP 200 response code but without really adding the object to my database.
EDIT: I m using supertest (https://github.com/visionmedia/supertest)
How can I do?
request
.post('/users')
.send({
message : JSON.stringify({
date: Math.round((new Date()).getTime() / 1000),
type_fiche: 'test',
id_fiche: 123
})
})
.expect(200)
.end(done);
});
EDIT 2: Is it possible to make something like a mock? Like faking a request?
You know that if I post something, it's that I need to insert something in my database right ?
I dont want to insert anything at all during myintegration tests, just test the result http response code.
I mean, admiting that I have an url like /client, and I post a new client on it. It will create a new row in the table. I dont want any row to be inserted, but I need to test the response code of the request.
Is that possible?
I would suggest adding sinon.js into the mix or any other mocking library of your choice. It will probably require quite a bit of refactoring in order to inject the mocked components.
The main idea is to mock user repository which encapsulates all db communication with user data and mock it in tests. Then you will inject mocked repository into router and test express app with supertest. Check out the example of testing imaginary user API for GET request.
var routerFactory = require('../path/to/router/factory');
describe('app router', function () {
var app, repository, router;
beforeEach(function () {
app = require('express')();
repository = createFakeUserRepository();
router = createRotuter(repository);
});
describe('getting user by id', function () {
beforeEach(function () {
app.use('/test'm router);
testedApp = supertest(app);
});
describe('GET /user/id', function (){
beforeEach('setup for valid response', function () {
repository.getById.returns(Promise.resolve({ expected: 'valid response' }))
})
it('returns 200', function (done){
testedApp.get('/test/user/id')
.expect(200, JSON.stringify({expected: 'valid response'}), done);
})
})
})
})
})
function createFakeUserRepository() {
return {
getById(): sinon:stub()
save(): sinon:stub()
};
}
function createRouter(fakeUserRepository) {
return routerFactory(fakeUserRepository);
}
You can use nock module. Its simple to use and you can get whatever data you want and you can test it.
Ex: nock('http://example.com')
.get('/users')
.query(true)
.reply({results: [{id: 'pgte'}]});
Inside supertest you can test the 'id' value. For error cases you can use replyWithError. You can get more details here: https://www.npmjs.com/package/nock