MEAN Stack: post method is not reflecting in database - javascript

I'm trying to pass some data through HTTP post method but it is not reflecting in the database.
This is code.
addJobList(jobitem) {
let headers = new Headers();
headers.append('Content-Type','application/json');
var selected = {
companyTitle : jobitem.company,
jobTitle : jobitem.jobtitle,
location : jobitem.location
}
console.log(selected);
this.http.post('http://localhost:3000/api/appliedjobs', JSON.stringify(selected),{headers: headers})
.map(res => res.json());
}
//getting jobs form back-end
getAppliedjobList() {
if (this.jobslist) {
return Promise.resolve(this.jobslist);
}
return new Promise( resolve => {
let headers = new Headers();
headers.append('Content-Type','application/json');
this.http.get('http://localhost:3000/api/appliedjobs',{headers: headers})
.map(res => res.json())
.subscribe(data => {
this.jobslist = data;
resolve(this.jobslist);
});
});
}
I've data in in the object called selected.
{companyTitle: "Facebook", jobTitle: "System Engineer", location: "torinto,canada"}
data from console. But this data is not get inserted into the database.
This is the code in my routes folder.
const jobList = require('../models/jobList');
router.post('/appliedjobs', function(req,res) {
console.log('posting');
jobList.create({
companyTitle: req.body.companyTitle,
jobTitle: req.body.jobTitle,
location: req.body.location
},function(err,list) {
if (err) {
console.log('err getting list '+ err);
} else {
res.json(list);
}
}
);
});
I'm not getting any error just the data is not getting inserted into the database.
This is my model
var mongoose = require('mongoose');
const joblistSchema = mongoose.Schema({
companyTitle: String,
jobTitle: String,
location: String,
});
const JlSchema = module.exports = mongoose.model('JlSchema',joblistSchema,'joblist');

You don't need to encode your data like in this example and you must return your this.http.post.
addJobList(jobitem) {
let headers = new Headers();
headers.append('Content-Type','application/json');
const selected = {
companyTitle : jobitem.company,
jobTitle : jobitem.jobtitle,
location : jobitem.location
}
return this.http.post('http://localhost:3000/api/appliedjobs', selected, { headers: headers })
.map(res => res.json());
}
To use it you need to subscribe to your addJobList method, http.post is an observable and needs to be subscribed to make the http call :
addJobList(theJobItem).subscribe(data => console.log(data));

Related

how can i do Multiple Request using Promise.all using this parameters?

today I had some problems with my code.. the thing is I have to create a multiple POST request to the API to pass users to a group, so.. the API request is:
POST /users/user-group-membership
{
"userId": "string",
"groupId": 0,
"isActive": true,
}
Basically i have to grab from the users table the userId from each user and for each userId create a multiple request... so what i did was:
const moveTogroup = async (
token: string,
userId: string,
groupId: number,
): Promise<any> => {
const res = await axios({
method: 'POST',
url: `${API}/users/user-group-membership`,
data: { userId: userId, groupId: groupId },
headers: {
Authorization: `Bearer ${token}`,
},
});
const { data } = res;
return data;
};
export const moveAllGroup = (
token: string,
): ThunkAction<void, State, null, UsersActions> => {
return async (dispatch, getState) => {
const { userId, groupId } = getState().FleetUsers;
const convert = userId.toString();
console.log(convert);
dispatch(moveUserToGroupRequest());
try {
const userPromises = userId.map(() =>
moveTogroup(token, convert, groupId),
);
const move = await Promise.all(userPromises);
console.log('moving:', move);
dispatch(moveUserToGroupSuccess(move));
Swal.fire('Saved', 'Your Changes has been saved', 'success');
} catch (error) {
dispatch(moveUserToGroupFailure(error));
Swal.fire('Error', error, 'error');
}
};
};
But as you see this only works for one userId, I grabbing from the state the userId and the groupId, converting the userId to string, and voila is working perfectly, only what I want is depending how much userId I have in the state replied to the request for creating multiple requests and when the user selects in table 2 or 3 users, he or she can move them easily.
If your userId var contains all userIds, you must map it to recover specific information about each userId :
userId.map((elt) => {
const convert = elt.toString();
moveTogroup(token, convert, groupId),
});

Ionic calling submit method in another method is not working properly

Below mentioned is my submit method will post some data to the server when I click on a submit button.
it is working well when the action is performed manually. but I don't want to press submit button every time I want to call this after input texts were filled for this I'm calling this method in another method at that time it is not posting anything it is giving undefined can anyone help me on this
start() {
SMSReceive.startWatch(
() => {
document.addEventListener('onSMSArrive', (e: any) => {
var IncomingSMS = e.data;
this.smsaddress = IncomingSMS.address;
this.smsbody = IncomingSMS.body;
if (this.smsbody.includes("HELLO") || this.smsbody.includes("HI")) {
alert("Data : " + this.smsbody + this.smsaddress);
const obj={
smsbody:this.smsbody,
smsaddress:this.smsaddress
}
this.submit(obj);
} else {
alert("resetting")
this.resetdata();
}
})
},
() => { console.log('watch start failed') }
)
}
submit(msg) {
let headers = new Headers();
headers.append('content-Type', 'application/json');
this.http.post(this.ip + "/api/route", { headers: headers }).pipe(map(res => res.json()))
.subscribe(data => {
alert(JSON.stringify(data));
this.presentToast('Message has been submitted successfully', false, 'bottom');
this.resetdata();
})
}; ```
You forget to pass data in post request
submit(msg) {
let headers = new Headers();
headers.append('content-Type', 'application/json');
this.http.post(this.ip + "/api/route",msg, { headers: headers },).pipe(map(res => res.json()))
.subscribe(data => {
alert(JSON.stringify(data));
this.presentToast('Message has been submitted successfully', false, 'bottom');
this.resetdata();
})

Data does not update in view

I am creating an update function in my ionic 4 frontend which has a form to update user info. When I try to change the name, for example, it is updated in the database but is not displayed in the view through interpolation unless I logout and log back in. Here is my update method in the frontend.
updateInfo() {
if (!this.updateForm.valid) {
this.invalidUpdate();
} else {
if (!(this.name === "")) {
var nameObj = {
name: this.name
};
this._userService.updateName(nameObj).subscribe(
data => {
console.log(data);
this.getUserNamePoints();
},
error => {
this.updateFail();
}
);
}
};
this.getUserNamePoints();
}
}
And here is the method updateName(name) in the service
updateName(name) {
var headers = new Headers();
headers.append(
"Authorization",
"Bearer " + this._authService.getAuthorizationToken()
);
headers.append("Content-Type", "application/json");
return this.http
.post(environment.apiUrl + "/user/updateName", name, {
headers
})
.map(res => res.json());
}
This is the method getUserNamePoints() which is also called in the constructor:
getUserNamePoints() {
this._authService.getPoints().subscribe((res: any) => {
this.current = res.data;
this.clientName = res.name;
});
}
And here is the interpolation I am performing:
<h2>
<ion-text color="secondary" style="font-weight:bold">
Hello, {{ clientName }}!</ion-text
>
</h2>
This is my backend method:
module.exports.updateName = function(req, res, next) {
User.findByIdAndUpdate(
req.decodedToken.user._id,
{
$set: req.body
},
{ new: true }
).exec(function(err, updatedUser) {
if (err) {
return next(err);
}
res.status(200).json({
err: null,
msg: "Name was updated successfully.",
data: req.decodedToken.user.name
});
});
};
I think the problem is in your backend. I can see that you are sending the data from the decoded token and the token is encoded when you login, so it does not have the updated data.
res.status(200).json({
err: null,
msg: "Name was updated successfully.",
data: req.decodedToken.user.name
});
Can you show me how are you retrieving the data of the user from your backend when you call the method "getUserNamePoints();" ? Are you looking for the user data in your database or in the decoded token?

Dynamically adding post at the site using Observables (Angular)

I need to display posts dynamically on my home page. I have textarea above the post lists and my goal is to display new post immediatelly after it would be added, on the top of the post list. Component with textarea form is called add-post-component and it use onSubmit event:
onAddPostSubmit() {
if (this.authService.loggedIn()) {
const post = {
content: this.content,
creator_username: JSON.parse(localStorage.getItem('user')).username,
rate: 0
};
this.postsService.addPost(post).subscribe(data => {
if (data.success) {
console.log('Post added');
this.router.navigate(['/']);
} else {
console.log('Post not added' + JSON.stringify(data));
this.router.navigate(['/']);
}
});
} else {
console.log('Not logged');
return false;
}
}
Component of my main page is called Feed-component
this.postsService.getPosts().subscribe(response => {
this.posts = response.posts.reverse();
}),
err => {
console.log(err);
return false;
};
this.subscription = this.postsService.fetchPost().subscribe(post => {
this.postsService.getPosts().subscribe(response => {
this.posts = response.posts.reverse();
}),
err => {
console.log(err);
return false;
};
});
Both components use posts service:
getPosts() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('http://localhost:3000/posts/fetch', {headers: headers})
.map(res => res.json());
}
addPost(post) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.subject.next({post});
return this.http.post('http://localhost:3000/posts/add', post, {headers: headers})
.map(res => res.json());
}
fetchPost(): Observable<any> {
return this.subject.asObservable();
}
As you can see, I use Observable methodology to process data between components. The problem which I have is that post list is updating after I add post to database, but without the last added post. So if I would add two posts - 1) 'abc' and 2) 'cba', after send 'abc' anything happened, and when I add 'cba' list will be updated with 'abc' on the top.
I think the case is that addPost method is calling after getPosts and fetchPost.
How to fix that?

415 (Unsupported Media Type) with REST Post request

I have a react component that when a checkbox is pressed, it calls a rest api, post request with a single parameter.
I put a breakpoint in the webapi and its never hit, still I get a 415 unsopported media type on the component
react js component (see onchange event)
import React, { Component } from 'react';
import { Table, Radio} from 'antd';
import { adalApiFetch } from '../../adalConfig';
import Notification from '../../components/notification';
class ListTenants extends Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
fetchData = () => {
adalApiFetch(fetch, "/Tenant", {})
.then(response => response.json())
.then(responseJson => {
if (!this.isCancelled) {
const results= responseJson.map(row => ({
key: row.ClientId,
ClientId: row.ClientId,
ClientSecret: row.ClientSecret,
Id: row.Id,
SiteCollectionTestUrl: row.SiteCollectionTestUrl,
TenantDomainUrl: row.TenantDomainUrl
}))
this.setState({ data: results });
}
})
.catch(error => {
console.error(error);
});
};
componentDidMount(){
this.fetchData();
}
render() {
const columns = [
{
title: 'Client Id',
dataIndex: 'ClientId',
key: 'ClientId'
},
{
title: 'Site Collection TestUrl',
dataIndex: 'SiteCollectionTestUrl',
key: 'SiteCollectionTestUrl',
},
{
title: 'Tenant DomainUrl',
dataIndex: 'TenantDomainUrl',
key: 'TenantDomainUrl',
}
];
// rowSelection object indicates the need for row selection
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
if(selectedRows[0].key != undefined){
console.log(selectedRows[0].key);
const options = {
method: 'post',
body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
config: {
headers: {
'Content-Type': 'application/json'
}
}
};
adalApiFetch(fetch, "/Tenant/SetTenantActive", options)
.then(response =>{
if(response.status === 200){
Notification(
'success',
'Tenant set to active',
''
);
}else{
throw "error";
}
})
.catch(error => {
Notification(
'error',
'Tenant not activated',
error
);
console.error(error);
});
}
},
getCheckboxProps: record => ({
type: Radio
}),
};
return (
<Table rowSelection={rowSelection} columns={columns} dataSource={this.state.data} />
);
}
}
export default ListTenants;
and the webapi method
[HttpPost]
[Route("api/Tenant/SetTenantActive")]
public async Task<IHttpActionResult> SetTenantActive([FromBody]string clientid)
{
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
var allTenants = await tenantStore.Query().Where(x => x.TenantDomainUrl != null).ToListAsync();
foreach(Tenant ten in allTenants)
{
ten.Active = false;
await tenantStore.UpdateAsync(ten);
}
var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.clientid == clientid);
if (tenant == null)
{
return NotFound();
}
tenant.Active = true;
var result = await tenantStore.UpdateAsync(tenant);
return Ok(result);
}
Couple of things I noticed.
You're trying to do a POST request with a JSON body. On the client, your request looks fine.
As I understand the POST body is
{ clientid: 'some-client-id' }
The interesting thing is in the web API you receive it as
public async Task<IHttpActionResult> SetTenantActive([FromBody]string clientid)
This is possibly the culprit. Your API is expecting a string as a POST body where it is a json object. Have you tried changing the type to dynamic or JObject?
So, essentially,
public async Task<IHttpActionResult> SetTenantActive([FromBody]dynamic clientRequest)
OR
public async Task<IHttpActionResult> SetTenantActive([FromBody]JObject clientRequest)
Alternately,
If you want to continue using your API as is, then you can just change the request you’re making from the client to ’some-client-id’ instead of { clientid: 'some-client-id' }
Change
const options = {
method: 'post',
body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
config: {
headers: {
'Content-Type': 'application/json'
}
}
};
to
const options = {
method: 'post',
body: JSON.stringify({ clientid : selectedRows[0].key.toString() }) ,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
Check your server settings. By default it should support json but its better to verify it. Also try to clear Accept header in yor api code and set to * which means all types.
Moreover check adalApiFetch method. What headers it send? Is the format of Content-Type used & set correctly?
For a simple RESTFul call like that you could follow suggestion naming conventions along with HTTP verbs that better clarifies the intention and simplify the call itself. No need to over complicate the API model for such a simple call.
Something like
[HttpPut] // Or HttpPost. PUT is usually used to update the resourcce
[Route("api/Tenant/{clientid}/Active")]
public async Task<IHttpActionResult> SetTenantActive(string clientid) {
var tenantStore = CosmosStoreFactory.CreateForEntity<Tenant>();
var allTenants = await tenantStore.Query().Where(x => x.TenantDomainUrl != null).ToListAsync();
var updates = new List<Task>();
foreach(Tenant ten in allTenants) {
ten.Active = false;
updates.Add(tenantStore.UpdateAsync(ten));
}
await Task.WhenAll(updates);
var tenant = await tenantStore.Query().FirstOrDefaultAsync(x => x.clientid == clientid);
if (tenant == null)
{
return NotFound();
}
tenant.Active = true;
var result = await tenantStore.UpdateAsync(tenant);
return Ok(result);
}
And on the client
const rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
if(selectedRows[0].key != undefined){
var clientid = selectedRows[0].key;
console.log(clientid);
var url = "/Tenant/" + clientid + "/Active"
const options = {
method: 'put'
};
adalApiFetch(fetch, url, options)
.then(response => {
if(response.status === 200){
Notification(
'success',
'Tenant set to active',
''
);
}else{
throw "error";
}
})
.catch(error => {
Notification(
'error',
'Tenant not activated',
error
);
console.error(error);
});
}
},
getCheckboxProps: record => ({
type: Radio
}),
};
Why are you using post? From a 'REST`y point of view, it is used to create an entity (a tenant in your case).
The simple request intended can be solved via GET with the clientid as part of the route:
[HttpGet]
[Route("api/Tenant/SetTenantActive/{clientid}")]
public async Task<IHttpActionResult> SetTenantActive(string clientid)
{
// ...
}

Categories

Resources