I am trying to post data from a python script to a Next js server.
#python script
import requests
post_data = {'username':'bob', 'id' : 32}
# POST some form-encoded data:
post_response = requests.post(url='http://localhost:3000/foo', data=post_data)
I do get a request on a server, but I do not know how to retrieve the data in getInitalProps(). I have looked at the documentation but there seems to be no such information.
static async getInitialProps({props, req})
{
console.log('request data: ', req.data);
}
Crashed into the very same problem and found the solution well hidden in the Next.JS forums.
In short, first you need the Urlencoded Body Parser library to help parse the HTTP request object. Using npm to install it:
npm install --save urlencoded-body-parser
Then in your code file, you call its function to get an object with the post variables in it:
import parse from 'urlencoded-body-parser';
static async getInitialProps(context)
{
if (context.req.method === "POST") {
const data = await parse(context.req);
console.log("request data: ", data);
}
}
Results, based on question sample data:
{
"username": "bob",
"id" : "32"
}
It should be like this:
static getInitialProps ({ query: { data } }) {
console.log('request data: ', data);
}
please not that you also need to pass the data in server.js:
server.get('/foo', (req, res) => {
return app.render(req, res, '/pageFoo', req.query)
})
Related
I am trying to implement a feature where I have an input on this route to make a live search of employees in the database
app.get('/delete' , isLoggedIn , (req , res) => {
res.render('pages/delete')
})
This route serves the search input. How do I create a live search based on a keyup event listener that sends the data to mongoDb/mongoose to search and return the results on the page?
I know how to do the event listener to get what is typed like so which is in the delete.js file
const deleteSearchInput = document.querySelector('#search-input');
deleteSearchInput.addEventListener('keyup' , (e) => {
let search = e.target.value.trim()
})
How do I send the value "e" to a post route to do the search and return it to the page
AJAX (using the JavaScript fetch API). AJAX allows JavaScript to send requests to the server without reloading.
const deleteSearchInput = document.querySelector('#search-input');
deleteSearchInput.addEventListener('keyup' , (e) => {
let search = e.target.value.trim();
fetch('/delete', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({search})
}).then(res =>
res.json()
).then(data => {
console.log(data.result); // <-- success!
}).catch(err => {
alert('error!');
console.error(err);
});
});
Then you have changes to make to the server side. Since you're sending a POST request, you need to create a handler to POST:
app.post('/delete', isLoggedIn, (req, res) => {
res.send('success!');
});
This will handle post requests, and only post requests. Now to get the value of whatever you sent to the server, we need to use an npm package called body-parser, which parses the incoming request. Run the following command in shell:
npm i body-parser
Then at the top of your server file before declaring your routes import and use the body-parser library:
const bodyParser = require('body-parser');
app.use(bodyParser.json()); // <-- add the JSON parser
Finally change your handler again:
app.post('/delete', isLoggedIn, (req, res) => {
const { search } = req.body;
console.log(search);
// ... do whatever you want and send a response, e.g.:
const result = 'my awesome message';
res.json({ result });
});
And that's how you do it.
I am working on project containing app and landing pages. We are using Nodejs with Axios and VueJs for app part. But for landing pages, it is simple jQuery. I must do some API calls for landing pages, but I am not able to use NodeJs result in jQuery to serve data in my landing pages. I am new at NodeJs and these technologies.
Here are my codes:
my Routes :
const router = express.Router();
...
router.get('/api/items', myApiController.getItems);
NodeJs controller
module.exports.getItems = (req, res) => {
const response = myApiController.getItems();
if (response.status === 200) {
res.send({
status: 200,
data: response.data
})
} else {
res.send({
status: 404,
data: null
})
}
}
my main script :
$.get("/api/items", function(data, status){
alert("Data: " + data);
var mylist = $("#mylist");
$.each(data, function(item) {
mylist.append($("<option />").val(item.name).text(item.name));
});
});
Even if I am getting status:200 the nodejs is returning HTML of page 404.
I do not find the cause, And honestly I do not understand the reason. It seems it is try to get a page does not exist, but I am requesting a json from function.
I try to replace contoller method call by a trash json but nothing work.
Here is what I try:
router.get('/api/items', function(req, res){
console.log('cc');
return res.json([{
'toto': 'toto',
'tata': 'tata',
}]);
});
It seems routes definitions issue, but I do not know how to fix. Could this have something with express Router ? Could you please explain me and help me to fix this? Thanks
When you respond with a string, the content type will be HTML. Try this, which removes the res.json call:
router.get('/api/items', function(req, res){
console.log('cc');
return [{
'toto': 'toto',
'tata': 'tata',
}];
});
I'm new to Node.js but I understand that it's on the server-side. When I run my app.js file in Terminal, it sends the text message, but what I'm ultimately trying to do is have the user finish the form, and upon button press, send them a text message to verify their submission. I'm using the Twilio service to help accomplish this. It's currently not sending a message on button press.
Here's my app.js file:
var accountSid = process.env.TWILIO_ACCOUNT_SID;
var authToken = process.env.TWILIO_AUTH_TOKEN;
var client = require('twilio')(accountSid, authToken);
app.get('/testtwilio', function(req, res) {
client.messages.create({
to: "+1receivingNumber",
from: "+myTwilioNumber",
body: "Testing, testing, testing"
}, function(err, message) {
if (err) {
console.log(err);
} else {
console.log(message.sid);
}
});
})
And my Javascript file:
$('#buttons').on('click', function(e) {
$.ajax({
type: 'POST',
url: '/testtwilio',
data: {
"To": userCellPhone,
"From": "+1myTwilioNumber",
"Body": "Ahoy! Testing"
},
beforeSend: function(xhr) {
...
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
And lastly, my html button:
<button type="submit" id="buttons" class="buttons">SUBMIT</button>
Honestly, I'm not even sure this is possible, but I've been searching forever and can't really find any direct solution. Any help is appreciated!
Your app variable is undefined. If you want to use the express framework like in the tutorials you've followed, you need to register it in your app.js like follows:
var express = require('express');
var app = express();
Combined with the answers/comments about POST, that should see you on your way.
Nb. you'll need to install express in your node modules. From the command line in your root directory:
npm install --save express
nodeJs route expects GET. But your ajax makes POST request. Try:
app.post('/testtwilio', ...
I want to send an email from a webix application by clicking a button in the UI, which will send a post request through an ajax call to the node JS server at the backend.
The webix part looks like below:
{ id:'tb',
view: 'toolbar',
cols: [
{view:"button", id:"mail_btn", type:"icon", label:"SendEmail", tooltip:"Send an email", width:100, on: {onItemClick:function(){sendEmail()}} },
]
}
The callback function:
function sendEmail() {
var bodypart = {"message" : "This is a test mail"};
$.ajax({
type: 'POST',
url: '/appl/email',
data: bodypart,
success: function (data) {
console.log("success");
},
error: function(err){
console.log(err);
}
});
}
}
The above ajax call sends a request to the node JS where I am using sendmail npm package to achieve this. The code looks like below :
var sendmail = require('sendmail')();
app.post('/appl/email', sendmail());
function sendEmail() {
sendmail({
from: 'xyz#support.com',
to: 'abc#support.com',
subject: 'test sendmail',
html: 'Mail of test sendmail ',
}, function(err, reply) {
console.log(err && err.stack);
console.dir(reply);
});
}
However, I am getting below error :
Error: Route.post() requires callback functions but got a [object Undefined]
Is there a way to send email from webix itself without sending the request to node JS server ?
Or else how to use the sendmail npm package to achieve this the way I am trying ?
Any help would be appreciated.
Your issue is not in the way you are using sendmail, but rather in the way you are using express routes.
Here is a sample code I just whipped up that gave me the same error you got in your code.
const express = require('express');
const app = express();
app.get('/', doSomething());
function doSomething() {
console.log('this is a sample test');
}
app.listen(3000, () => console.log('server is running'));
The issue is that app.get, and the same would be true for app.post, has a certain signature it requires. The function that gets passed in is supposed to have the req and res arguments. You can also optionally add the next argument last.
This is how my above code would fixed.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
doSomething();
res.json('success');
});
function doSomething() {
console.log('this is a sample test');
}
I seem to be doing something wrong.
I have a student website that I want to scrape, but first I need to log in. Currently I have a python scraper that does it. The website logs in with a post request to a url containing a sid and PIN.
var login_url = 'https://example.com';
var formData = {
sid: 'username',
PIN: 'password'
}
How would I go about creating the same scraper but with javascript? I have seen the request library, which seems like what I want to use but cannot get it to work.
You need to use the request module to POST the form data to your endpoint. The response from the server will be in the call back to the .post() method.
const request = require('request');
// do not reassign "request", if you need to set properties us a different variable
// use the action= value from the form for the URL
const url = 'https://central.carleton.ca/prod/twbkwbis.P_ValLoginn';
const data = {
sid: 'username',
PIN: 'password',
};
request.post({ url: url, formData: data }, (err, response, body) => {
if (err) {
console.log('failed', err);
} else {
console.log('the response', body);
}
});
If you are interesting in parsing the resulting HTML I recommend using CheerioJS - much like jQuery but server side.