Updating/Deleting User Profile with React on Express - postgresql

I'm working on a web app with React on Express with a Postgresql database, and am working on trying to allow users the ability to delete/update their profiles. I've updated the controller, model, and routes for these changes, but I'm having an issue figuring out where to send the fetch request from the React component. Anytime I try to run a delete or an update I get the following on my terminal:
PUT /api/auth/1 400 3.468 ms - 24
--- undefined /robots.txt
I checked other threads on here and wasn't able to find how I can determine what URL I should point to for these functions. I think once I get that it should work as intended. Below are my auth routes and the functions I have set up, if anybody could suggest how I'd determine what URL to point this to I'd really appreciate it.
// handle profile update/delete
authRouter.route('/dashboard')
.get(usersController.show)
.put(usersController.update)
.delete(usersController.delete)
User Update/Delete functions:
handleUpdateSubmit(e, data, id) {
e.preventDefault()
console.log('clicked')
fetch(`/api/auth/${id}`, {
method: 'PUT',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then(res => res.json())
.then(res => {
this.setState({
fireRedirect: true,
redirectPath: '/dashboard'
})
}).catch(err => console.log(err))
}
userDelete(id) {
fetch(`/api/auth/${id}`, {
method: 'DELETE',
}).then(res => res.json())
.then(res => {
this.setState({
fireRedirect: true,
redirectPath: '/'
})
}).catch(err => console.log(err))
}
Please let me know if there's any information that'd be useful for figuring this out and I'll provide it immediately, thanks!

Forgot to follow up on this, the issue was with how my functions were ordered. I moved my authrouter.Route code beneath the login/logout/register functions and it's working as expected.

Related

Extension times out when making request from the web view

I am making an extension and trying to make a request to my local server from the web view. I am using axios to make the requests. But for some reason all of the request times out after 5 minutes as there would be some kind of default configuration. I know it is not axios fault, because I also tried fetch api and both their timeout configurations works fine.
The error I get is just "Network Error", but it is always after 5 minutes.
Sample code with axios and fetch in my web view script tags:
axios.get("https://localhost:7074/api/SaltEstimate",{headers: { keepAlive: true }}).then(
(/** #type {any} */ response) => {
console.log(response);
}
).catch(function (/** #type {{ toJSON: () => any; }} */ error){
console.log(error.toJSON());
});
fetch('https://localhost:7074/api/SaltEstimate')
.then(response => response)
.then(data => console.log(data));
</script>

Nodemailer. createTestAccount and cypress: generate same email address

I created an E2E to test for signups, using Nodemailer with Ethereal.
When the test runs the first time everything ends smoothly, but when I executed it a second time the test, for some reason, breaks.
While investigating the above issue, I noticed that the createTestAccount returns the same email address (unless cypress is restarted).
Here's the function code for createTestAccount: https://github.com/nodemailer/nodemailer/blob/master/lib/nodemailer.js#L58.
Is createTestAccount using an internal cache?
If yes, is there a way to disable it (besides setting and process.env.ETHEREAL_CACHE to false)?
Based on the current version (6.7.4) of code, it's not possible to disable the cache any other way than setting the env variable ETHEREAL_CACHE to something different than ['true', 'yes', 'y', '1'].
Aka process.env.ETHEREAL_CACHE needs to be false
Keep in mind that this is OS level env variable. Not the ones setup in Cypress.
And the best thing is the great documentation which mentions ETHEREAL_CACHE variable ...
const request = require("request");
async function createEmail (callback) {
request.post({
headers: { "content-type" : "application/json" },
method: "POST",
url: "https://api.nodemailer.com/user",
body: Buffer.from(
JSON.stringify({
requestor: "nodemailer",
version: "6.7.8"
})
)
}, (err, res, body) => {
if(err)
return callback("Failed to handle request!");
const data = JSON.parse(body) || null;
if(typeof(data) !== "object" || typeof(data.status) !== "string")
return callback("Failed to resolve data");
delete data.status;
return callback(false, data);
});
};
createEmail((err, account) => {
if(err)
return console.log(err);
console.log(account);
});

Service workers "sync" operation is working while its offline?

I have a PWA project where I send the data to server. During this process, if the user is offline then the data is stored in indexedDb and a sync tag is registered. So, then when the user comes online that data can sent to the server.
But In my case the sync event gets executed immediately when the we register a sync event tag, which means the data is tried to be sent to server while its offline, which is not going to work.
I think the sync event supposed to fire while its online only, what could be issue here ?
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
This is how I register my sync tag
function onFailure() {
var form = document.querySelector("form");
//Register the sync on post form error
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready
.then(function (sw) {
var post = {
datetime1: form.datetime1.value,
datetime: form.datetime.value,
name: form.name.value,
image: form.url.value,
message: form.comment.value
};
writeData('sync-comments', post)
.then(function () {
return sw.sync.register('sync-new-comment');
})
.then(function () {
console.log("[Sync tag registered]");
})
.catch(function (err) {
console.log(err);
});
});
}
}
And this is how the sync event is called
self.addEventListener('sync', function (event) {
console.log("[Service worker] Sync new comment", event);
if (event.tag === 'sync-new-comment') {
event.waitUntil(
readAllData('sync-comments')
.then(function (data) {
setTimeout(() => {
data.forEach(async (dt) => {
const url = "/api/post_data/post_new_comment";
const parameters = {
method: 'POST',
headers: {
'Content-Type': "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
datetime: dt.datetime,
name: dt.name,
url: dt.image,
comment: dt.message,
datetime1: dt.datetime1,
})
};
fetch(url, parameters)
.then((res) => {
return res.json();
})
.then(response => {
if (response && response.datetimeid) deleteItemFromData('sync-comments', response.datetimeid);
}).catch((error) => {
console.log('[error post message]', error.message);
})
})
}, 5000);
})
);
}
});
you mention
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
So I'm not sure which case is the one failing.
You are right that the sync will be triggered when the browser thinks the user is online, if the browser detects that the user is online at the time of the sync registration it will trigger the sync:
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Also, from the workbox documentation
Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts.

Github API doesn't retrieve all the users when requested

I have a project where I need to retrieve all the issues from a repo. I've been practicing with the atom repository and I am using the GitHub API.
I use axios get function and the request I'm making is the following.
axios.get('https://api.github.com/repos/atom/atom/issues',
{
headers: { 'Accept': 'application/vnd.github.VERSION.raw+json' },
params: {'state': 'all'}
})
.then((response) => {
console.log(response);
})
.catch((error) =>{
console.log(error);
});
But there are 772 issues and it is only retrieving 30 issues.
How can I retrive them all? am I missing something in the header or the params.
Ive also tried without params and the header. And also adding filter: all to the params and I still get 30 issues.
Thanks in advance.

how to deal with mongodb race condition in integration test

I have a mongoose schema with a unique field and I am trying to write a backend (express) integration test which checks that POSTing the same entity twice results in HTTP 400. When testing manually behaviour is as excpected. Automatic testing however requires a wait:
it('should not accept two projects with the same name', function(done) {
var project = // ...
postProjectExpect201(project,
() => {
setTimeout( () => {
postProjectExpect400(project, done);
},100);
}
);
});
The two post... methods do as named and the code above works fine, but if the timeout is removed, BOTH requests receive HTTP 200 (though only one entity created in the database).
I'm new to those technologies and I'm not sure what's going on. Could this be a mongodb related concurrency issue and if so how should I deal with it?
The database call looks like this:
Project.create(req.body)
.then(respondWithResult(res, 201))
.catch(next);
I already tried connecting to mongodb with ?w=1 option btw.
Update:
To be more verbose: Project is a mongoose model and next is my express error handler which catches the duplicate error.
The test functions:
var postProjectExpect201=function(project, done, validateProject) {
request(app)
.post('/api/projects')
.send(project)
.expect(201)
.expect('Content-Type', /json/)
.end((err, res) => {
if (err) {
return done(err);
}
validateProject && validateProject(res.body);
done();
});
};
var postProjectExpect400=function(project, done) {
request(app)
.post('/api/projects')
.send(project)
.expect(400)
.end((err, res) => {
if (err) {
return done(err);
}
done();
});
};