So I have a web api that is set up to generate a token for to return when you send it a username and password that are the same this works through postman if you give a body like so
this works it gives you a token and the correct information but when i do it from chrome, firefox or ie it gives me an error my code is this,
var d = {
username: Uname,
surname: Pword,
grant_type: "password",
client_id: "099153c2625149bc8ecb3e85e03f0022",
};
console.log(d);
var self = this;
return (
axios.post('http://localhost/hydraauth/oauth/token', {
headers: {
'Content-Type': 'application/json',
},
data: d
}).then(function (response) {
console.log(response.data)
self.setState({
isLoggedIn: true,
Uname: Uname,
}, function () {
sessionStorage.setItem("Login", true);
sessionStorage.setItem("Uname", Uname)
window.location.href = "/";
});
}).catch(function (error) {
if (error.response){
console.log(error.response)
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
window.alert("Incorrect Username Or Password Or Unauthorized To Access This.")
}
})
);
which gives me this error in chrome
here is the error expanded
image of the network tab in chrome the response tab is empty
Axios has an issue with sending data via body so you need to use npm plugin query string
and use it like so
axios.post("http://localhost/hydraauth/oauth/token", querystring.stringify({ "username": Uname, "password": Pword, "grant_type": "password", "client_id": "eyJjbGllbnRfaWQiOiJTYXZ2eS1Dcm0tUmVhY3QtSnMtU3lzdGVtIn0" }))
Related
I am making my web using React no backend. I want to integrate MailChimp to my app but it's giving me the following error:
ContactUs.jsx:40 POST http://localhost:3000/3.0/lists/{api-key} 404 (Not Found)
function sendData(event) {
const { name, email, subject } = state;
const userData = {
members: [
{
"email_address": email,
status: "subscribed",
merge_fields: {
"FNAME": name,
"MESSAGE": subject,
}
}
]
}
console.log(userData)
fetch('/3.0/lists/{api-key}', {
method: 'POST',
headers: {
'auth': "saad:153b-us12",
'Content-Type': 'application/json',
},
body: JSON.stringify(
userData
)
}).then(response => console.log(response))
.catch(error => console.error(error))
event.preventDefault();
}
You are sending the request to the localhost, which is your app url on your machine. According to the Mailchnimp docs you should send the request to https://<dc>.api.mailchimp.com url. Just set the correct url in the fetch function.
I'm unable to get the Strapi change-password api working (using latest version 4.4.1). The following code returns a 400 - Bad Request.
async function changePassword() {
fetchURL = `${dbPath}api/auth/change-password`;
fetchHeader = new Headers();
fetchHeader.append("Authorization", `Bearer ${jwtString}`);
fetchHeader.append("Content-Type", "application/json");
fetchCommand = new Request(fetchURL, {
method: "POST",
headers: fetchHeader,
body: JSON.stringify({
"data": {
"currentPassword": oldPasswordInput.value,
"password": newPasswordInput.value,
"passwordConfirmation": confirmPasswordInput.value
}})
})
try {
response = await fetch(fetchCommand);
if (response.ok) {
data = await response.json();
writeLogRecord(userId, 0, 0, "Password change successful");
modalText.innerText = "Password successfully changed";
displayModalContainer();
} else {
modalText.innerText = "Password not changed";
displayModalContainer();
}
} catch (err) {
console.log("User Fetch error", err);
}
}
Chrome console shows me this:
POST http://localhost:1337/api/auth/change-password 400 (Bad Request)
I've looked on both the Strapi Discord and Strapi forums but have found no help.
Can anyone point out to me what I'm doing wrong?
(Added 10/3/2022)
The Strapi docs show how to do this via axios:
axios.post(
'http://localhost:1337/api/auth/change-password',
{
currentPassword: 'currentPassword',
password: 'userNewPassword',
passwordConfirmation: 'userNewPassword',
},
{
headers: {
Authorization: 'Bearer <user jwt token>',
},
}
);
Updated JS
async function changePassword() {
fetchURL = `${dbPath}api/auth/change-password`;
fetchHeader = new Headers();
fetchHeader.append("Authorization", `Bearer ${jwtString}`);
fetchHeader.append("Content-Type", "application/json");
fetchCommand = new Request(fetchURL, {
method: "POST",
headers: fetchHeader,
body: JSON.stringify({
currentPassword: oldPasswordInput.value,
password: newPasswordInput.value,
passwordConfirmation: confirmPasswordInput.value
})
})
try {
response = await fetch(fetchCommand);
if (response.ok) {
data = await response.json();
modalText.innerText = "Password successfully changed";
displayModalContainer();
} else {
modalText.innerText = "Password not changed";
displayModalContainer();
}
} catch (err) {
console.log("User Fetch error", err);
}
Still returns POST http://localhost:1337/api/auth/change-password 400 (Bad Request)
And I figured this out - posting in case anyone else runs into this. Below is the correct way to format the payload of this request. The data tag is necessary, but it and the field names should not be in quotes. Note this is a modification to my original post, not the second one I tried.
data: {
currentPassword: currentPasswordInput.value,
password: newPasswordInput.value,
passwordConfirmation: confirmPasswordInput.value
I am following a MailChimp API tutorial
When I test the API, I get a 401 response saying my API key is invalid.
Error -
Status: 401
"Your API key may be invalid, or you've attempted to access the wrong datacenter."
I have yet to register a domain yet, this is being testing using a local server. Could this be error be caused by MailChimp's refusing the request for another reason, perhaps CORS?
app.post('/signup', (req, res) => {
// Get form data
const { email } = req.body;
// Make sure field is filled
if(!email) {
res.redirect('/html/fail.html');
return;
}
// Construct req data
const data = {
members: [
{
email_address: email,
status: 'subscribed'
}
]
}
// Convert to JSON
const postData = JSON.stringify(data);
const options = {
url: 'https://us19.api.mailchimp.com/3.0/lists/listID',
method: 'POST',
headers: {
Authorization: 'auth xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us19'
},
body: postData
};
request(options, (err, response, body) => {
if(err) {
console.log(err);
res.redirect('/html/fail.html');
} else {
if(response.statusCode === 200) {
res.redirect('/html/success.html');
} else {
console.log(response.body);
res.redirect('/html/fail.html');
}
}
});
})
I tried running the same code in request in PostMan and I got back a 200 response.
I was initially importing the API key from a config file, that I had not destructured...
I can't seem to get the correct response headers when my code enters bcrypt.compare. I thought it was a cors issue at first but I still get the correct response if I entered the wrong and "user does not exist" is displayed.
Here's my api server side code in express
router.post("/api/signIn", (req, res) => {
const { user, password } = req.body;
const queryString = "SELECT * FROM users WHERE user_id = ?";
db.query(queryString, [user])
.then(result => {
if (result.length > 0) {
const hash = result[0].password;
//here bcrypt.compare works server side or with cURL but won't set the response headers in the browser
bcrypt
.compare(password, hash)
.then(same => {
if (same === true) {
console.log("correct password");
res.status(200).json({
code: 200,
message: "correct password"
});
} else {
res.status(401).json({
code: 401,
message: "incorrect password"
});
}
})
.catch(err => console.log(err));
} else {
//this one works though and i can get the response in the browser so it can't be a cors issue
console.log("user does not exist");
res.status(200).json({
code: 401,
message: "User does not exist"
});
}
})
.catch(err => {
console.log("error" + err.message);
});
});
and this is the test function i use in react
const signIn = () => {
fetch("http://localhost:5000/api/signIn", {
method: "POST",
body: JSON.stringify({
user: userName,
password: password
}),
headers: {
"Content-Type": "application/json"
},
})
.then(res => res.json())
.then(response => alert(response.code + response.message))
.catch(err => alert(err));
};
so if i entered the wrong username that is not in the database, the alert function would show (code401User does not exist) but if i entered the correct user bcrypt.compare() doesn't seem to set the response for both correct and incorrect passwords and i would get (TypeError: failed to fetch). testing the api in cURL works though.
Got it, I forgot to put event.preventDefault() on the fetch function.
I'm using axios and an API to get a page's HTML, editing the HTML, and putting it back via a POST request to the API. I'm successful in retrieving and editing the HTML but I can't figure out how to put it back/change the webpage's HTML.
I tried using a PUT request instead of a POST request, but I get a 405 error that the PUT method is not allowed for the webpage.
axios.get(url, {
auth: {
username: USERNAME,
password: PASSWORD
},
headers: {
'Content-Type': 'application/json'
}
})
.then( (response) => {
version = response.data.version.number;
body = response.data.body.storage.value;
// takes the body HTML and formats all the links
newBody = middleware.formatLinks(body);
data = {
"type": "page",
'version': {'number': version + 1},
'body': {
'storage': {
'value': newBody,
'representation': 'storage'
}
}
}
// put the body HTML back into the page
axios.post(url, {
data: {
"type": "page",
'version': {'number': version + 1},
'body': {
'storage': {
'value': newBody,
'representation': 'storage'
}
}
}
}, {
auth: {
username: USERNAME,
password: PASSWORD
},
headers: {
'Content-Type': 'application/json'
}
})
.then( (response) => {
console.log(response.data);
})
.catch( (error) => {
console.log(error);
})
})
.catch( (error) => {
console.log(error);
})
I expect the page to now be updated with all the links formatted to my liking. However the page is unchanged. When I console.log(response.data) after making the post request, the output is a string of newBody, when I expect it to be the JSON object
data: {
'type': 'page',
'version': {'number': version + 1},
'body': {
'storage': {
'value': newBody,
'representation': 'storage'
}
}
}
As mentioned in my comment in #Aman Raj's answer, I have the code working in python but translating it to nodejs was giving me issues. So I circumvented my problem by calling my python script in nodejs with the python-shell package.
let {PythonShell} = require('python-shell');
...
const formatLinks = (id) => {
let options = {
mode: 'text',
pythonOptions: ['-u'], // get print results in real-time
scriptPath: './python/', // path to my python scripts
// pass in the page id, username, and password to API request
args: [id, USERNAME, PASSWORD]
};
PythonShell.run('script.py', options, (err, results) => {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
}
Your code seems fine. It may be possible that you are accessing an API which does not support editing it.
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the request method is known by the server
but is not supported by the target resource.