I have a built react front end, I used a simple boilerplate to connect the express with react. There seems to be SO many different ways to setup a SIMPLE RESTful api that I'm getting lost. I'm trying to do some very simple backend to front end communication.
I have express do a get request to push to the back and am using Axios to get the data:
AccountsDB is just basic JSON data for internal testing
[
{
"id": "5b68d6f13e2c773581221620",
"index": 0,
"firstName": "Josefa",
"lastName": "Lynch",
"pin" : 1234
}
]
Inside my express index.js I have a simple GET
app.get('/api/getAccounts', (req, res) => res.json(AccountsDB));
within my React I fetch the data with axois:
componentDidMount () {
axios.get ('/api/getAccounts')
.then (res => this.setState({ Accounts : res.data}));
}
Totally works. I display the account within the main react component.
Inside the component I also have a forum to "create" a a new account, and push it to the AccountsDB file just for internal testing (I'm learning backend, will connect mongoDB after).
My logic for POST method (found here Axios Cheet Sheet):
axios.post('/api/putAccounts', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Which I attach onto a button to post the data. I open up POST man and navigate to '/api/putAccounts' and see nothing.
I don't understand how to exactly gather the data into express. My silly attempt :
app.post('/api/putAccounts', (req,res) => {
// res.send("sent!") // post man see's this?
// var account = req.account;
// res.send(req.firstName);
});
To elaborate in more detail ...
React app is on -> localhost:3000
Express app is on -> localhost:8080
using webpack and a proxy:
devServer: {
port: 3000,
open: true,
proxy: {
'/api': 'http://localhost:8080'
}
under 'http://localhost:3000/admin' (in my react app) I have a button that has the axios.post that send the firstName : Fred and lastName : Flintstone to '/api/putAccounts'
I'm trying to have my express server catch the post so I can manipulate it and add it into a database.
Before I get into database stuff, I'm trying to make sure I understand how POST works (I understand GET). So I'm trying to get the data, and display it somewhere, this is what I mean by viewing it in postman.
Maybe I'm going about this all wrong, hence why the confusion.
In postman you need to send firstName and lastName in req body like below while making post request
{
"firstName": "Hi",
"lName": "Hello"
}
So that you can do req.body.firstName to get its value below
app.post('/api/putAccounts', (req,res) => {
const fName = req.body.firstName;
const lName = req.body.lastName;
res.json({"fName":fName, "lastName": lName});
});
Related
Hi getstream community,
I am building a feed application with react native and node.js. I am struggling to add activities using the getstream.io js client, but I can do it with react-native-activity-feed's <StatusUpdateForm/> component. I get the following error with the js client:
An error occured when submitting activity: Error: {"detail":"You don't have the permission to do this","status_code":403,"code":17,"exception":"NotAllowedException","duration":"0.16ms"} with HTTP status code 403
I've set up the backend to send me a user token and initialize a user feed:
const streamClient = stream.connect(STREAM_KEY, STREAM_SECRET, STREAM_ID);
gsToken = streamClient.createUserToken(decodedToken.user_id);
streamClient.feed('user', decodedToken.user_id);
In the frontend I render a feed using <StreaApp/> & <FlatFeed/>
I've set up the post screen to send a sample activity on press to the feed:
var client = stream.connect(config.stream.app.key, config.stream.app.token, config.stream.app.id);
var user_feed = client.feed('user', config.stream.app.userId);
user_feed.addActivity({
actor: config.stream.app.userId,
tweet: 'Hello World I am finally here',
verb: 'Tweet',
object: 1
})
.then(function(data) { console.log('Activity Added! ' + data)})
.catch(function(err) { console.log('An error occured when submitting activity: ' + err)});
SideNote: I would like to use the js client instead of the react-native package so I can have more flexibility with UI.
When using user tokens please make sure to call setUser
let feed = client.feed("user", "jack");
await client.setUser({name: 'Jack'});
await userFeed.addActivity({
actor: client.currentUser,
verb: "post",
object: "my object",
})
this will populate client.currentUser which you can use as actor as well as store the user data in the actor field.
I am new to React with node
Now I want to send data from node js(backend) to React js with response data. Actually, my situation is after signup from Google authentication I want to send that data to a React js (frontend).
router.get(
'/auth/google/callback',
passportGoogle.authenticate('google', {
failureRedirect: '/',
}),
(req, res) => {
const nameFirst = req.user.profile._json.displayName;
const picture = req.user.profile._json.image.url;
const email = req.user.profile.emails[0].value;
const id = req.user.profile.id;
const user = new User({
user_token: id,
name: nameFirst,
email: email,
picture: picture,
provider: 'Google',
dateSent: Date.now(),
});
User.findOne({ email: email }, (err, docs) => {
if (docs != null) {
// already exist
} else {
// send data `user` with routing [routing to /signupnext,]
}
});
What you are describing composes an issue between computer systems: how to communicate.
Using JSON and REST, you can develop a REST endpoint as a node service.
All a REST endpoint is, is an HTTP Service Adress that behaves in a specific way.
What you need to do, is develop a REST Endpoint within your Node application and call that endpoint using your React application.
You cannot just "Send" the data to a client application, the application has to request it.
If you re-write your call so that your React.JS calls an endpoint, Node.JS authenticates and returns the result back to React, that should work for you.
More information on Node rest endpoints: https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd
I'm making a call to an API in Node/Express in a React app, and regardless of where I put the fetch/axios call, my parsed body shows as undefined in my controller. I spent yesterday working with fetch, but tried axios for a change today, and here's the request:
axios({
method: 'post',
url: 'http://localhost:3000/users/sign_in',
data: {
email: "matthewharp#gmail.com",
password: "xxxxxxx"
}
})
.then(data => console.log(data))
.catch(err => console.log(err));
Now, here's the tricky part: console.log() statements in the Node controller AND the query file do trigger, so there's not a problem with the routing, and when I configure the query file to simply send a resource at random, ignoring the intended logic of searching by a body field, everything returns fine. But both fetch and axios result in undefined values for the req.body and any attribute therein. For instance, this action in the controller:
signIn(req, res, next) {
let user = {
email: req.body.email,
password: req.body.password
};
console.log("1: " + Object.keys(req.body));
console.log("2: " + req.body.email);
}
Will result in the following log to the console:
1: [object Object]
2: undefined
But a call to Object.keys() for the object in question returns an empty string.
I am using bodyParser, but as other questions have pointed out, that must be initialized before any route declaration - which I'm doing (I've abstracted configuration into a main-config.js file and a route-config.js files, and main contains bodyParser and is initialized first).
I'd greatly appreciate any help, and will happily provide more information and code snippets.
Edit: API code https://github.com/RainyDayMatt/abbas-tables-node-express-api/tree/mrh-add-user-code
So, I had implemented bodyParser incompletely. I had set up app.use(bodyParser.urlencoded({extended: true})) when initializing my main config file, but not app.use(bodyParser.json()).
Hello im trying to set up push notifications for my webapp.
I'm getting my subscription like I should.
It saves it to my database correctly.
It sends my notification like it should if there only is ONE user in the db
and i want to send to more than only one user :)
Im using:
Vue.js (framework)
Axios (post)
node.js (api)
mongoDB (database)
Here's my post to API.
await axios({
method: 'post',
url: 'API',
data: {
subscription: JSON.stringify(subscription),
storeId: storeId
},
headers: {
'Content-Type': 'application/json'
}
})
It registreres my post, but then i get an throw error.
that "Can't set headers after they are sent."
I'm using CORS in my app like this:
const cors = require('cors')
const app = express();
app.use(bodyParser.json());
app.use(cors())
app.use(morgan('combined'))
The way I'm handling the post from my website is by finding my subscriptions and then map through and say foreach subscription
webpush
//subscribe routes
app.post('/pushNotification', (req, res) => {
var storeId = req.body.storeId
res.setHeader('Content-Type', 'application/json');
console.log(storeId)
if (req.body.storeId != null) {
console.log('Test1')
//get pushSubscription object
//create payload
const payload = JSON.stringify({ title: 'push test' })
Push.find({
"storeId": storeId
},
'subscription', function(error, response) {
console.log('Test2')
console.log(response)
response.map(item => {
res.status(201).json({});
console.log('Test3')
var subscription = item.subscription
console.log(subscription)
webpush.sendNotification(subscription, payload).catch(err => console.error(err));
})
})
} else {
res.send("failed")
}
})
As i can read around somewhere is it im not setting headers or something right. I have used cors like in tutorials and stuff.
So it's like it is crashing because it iterates wrong.
but i can't see how.
ERROR MESSAGE:
Thanks in advance
you are getting this error because res.status(201).json({}) has already set the headers and sent back the response to the client but webpush.sendNotification also trying to set the headers.You should use only webpush.sendNotification(subscription, payload).catch(err => console.error(err));
res.json([body]) sets the corresponding header and sends the result:
Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().
So, first of all you don't need to set header manually.
second, If the response has more than one item, since you can't send multiple result for a request, you shouldn't use res.json in a map.
Moreover, be aware of webpush.sendNotification that it may send a result too.
I'm creating a web application and I'm curious how to send data to MySQL database in it. I have a function that is invoked when user presses button, I want this function somehow to send data to the MySQL server. Does anyone know how to approach this problem? I tried npm MySQL module but it seems the connection doesn't work as it is client side. Is there any other way of doing it? I need an idea to get me started.
Regards
You will need a server that handles requests from your React app and updates the database accordingly. One way would be to use NodeJS, Express and node-mysql as a server:
var mysql = require('mysql');
var express = require('express');
var app = express();
// Set up connection to database.
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret',
database: 'my_db',
});
// Connect to database.
// connection.connect();
// Listen to POST requests to /users.
app.post('/users', function(req, res) {
// Get sent data.
var user = req.body;
// Do a MySQL query.
var query = connection.query('INSERT INTO users SET ?', user, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
Then you can use fetch within a React component to do a POST request to the server, somewhat like this:
class Example extends React.Component {
constructor() {
super();
this.state = { user: {} };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
var self = this;
// On submit of the form, send a POST request with the data to the server.
fetch('/users', {
method: 'POST',
data: {
name: self.refs.name,
job: self.refs.job
}
})
.then(function(response) {
return response.json()
}).then(function(body) {
console.log(body);
});
}
render() {
return (
<form onSubmit={this.onSubmit}>
<input type="text" placeholder="Name" ref="name"/>
<input type="text" placeholder="Job" ref="job"/>
<input type="submit" />
</form>
);
}
}
Keep in mind that this is only one of infinite ways to achieve this.
It depends on how your application is organized, I will guess that you have a server that provides your React application code.
I would advise you to send the necessary information to your server (if there is any) using a module based on your preferences:
fetch built-in XHR api (https://developer.mozilla.org/en/docs/Web/API/Fetch_API)
request callback-based npm module (https://www.npmjs.com/package/request)
axios promise-based npm module (https://www.npmjs.com/package/axios)
If you are looking for a module/plugin doing all the work from client to database I don't know any and not sure there is because it is usually advised to use a proxy (a server to redirect but also to format or block requests between your client and the database).
Then, in your server you format the necessary information (if any) to be usable by your MySQL database, and then contact your MySQL database with the module of your choice, the first most popular module seems to be:
https://www.npmjs.com/package/mysql, but if you know another one or have other preferences go on. (For example with MongoDB we can use Mongoose to make requests easier)