Fetch POST puts payload into the name of the object - post

Hey i'm try to pass data from my browser, which uses React, to my API - which then manages the database. I can only get the API and database to work via Postman because when i Fetch POST the payload, it puts the payload into the name of the response object.
response = '{"username":"lolawdawd","email":"wadwa","password":"xiCm9RDsi8YM6vE"}': ''
This then stops the api from making use of the data. I've tried many different methods and cannot figure this out. My code for Fetch is as follows:
const handleSubmit = async (e) => {
e.preventDefault();
const input = {
username: user,
email: email,
password: pass
}
console.log(input);
try {
await fetch(`http://localhost:8000/api/register`, {
method: "POST",
body: JSON.stringify({
username: user,
email: email,
password: pass
}),
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
}})
navigate('/login');
} catch (err) {
console.log(err.message);
}
};

Related

Email sent but not received when using MSGraph API

When I Hit ms graph API with my Nodejs code to send the email, an email is sent with no error displayed but the email is received in the outlook sent email which I'm using
I have proper accessToken what happing behind this please help here
Code below
const sendNotification = async (from, message) => {
const access_token = await getAuthToken();
try {
const response = await axios({
url: `${GRAPH_ENDPOINT}/v1.0/users/${from}/sendMail`,
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
data: JSON.stringify(message),
});
console.log("sendNotification status", response.statusText);
} catch (error) {
console.log(error);
}
};

Unable to pass post variables in http request from Electron to Yii API

I want to make API (Get & Post) requests to an API build with Yii2 using Electron.
I have tried Axion, Fetch, HTTP, request modules and all of them gave me the same error:
data: {
name: 'PHP Notice',
message: 'Undefined index: username',
code: 8,
type: 'yii\base\ErrorException',
file: 'C:\xampp\htdocs\app\controllers\ApiController.php',
line: 898,
'stack-trace': [Array]
}
Here is the code for the action I want to call:
public function actionLogin(){
if(Yii::$app->request->isPost){
Yii::$app->response->format = Response::FORMAT_JSON;
$data = Yii::$app->request->post();
$username = $data['username'];
$password = $data['password'];
$device_token = $data['device_token'];
$prefix = substr($username, 0, 3);
$model = null;
}
}
And here is the code in Electron:
axios.post('http://localhost:8080/app/api/login', {
username: 'Fred',
psssword: 'Flintstone'
})
.then(function (response) {
console.log(response);
});
For some reason, the parameters are not passing to the action.
I have tried a lot of ways and this one seems to be the simplest.
P.S. all of the way I have tried gave the same error.
I have found the solution for this issue, the way it worked was:
const login = async(username, password)=>{
const data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
data.append('device_token', 'null');
await fetch(`http://localhost:8080/app/api/login`,{
method: 'post',
body: data
})
.then(res => res.json())
.then(data => {
if(data.status){
ipcRenderer.send('user:login', data.data.user_type, data.data.access_token);
}
else{
document.querySelector('#message').innerText = 'Wrong password or username';
document.querySelector('#message').style.display = 'block';
}
})
}

MS Graph Sample Application Integration Test not Working

I want to do what the MS Graph sample node app is doing in its integrationTests.js, but that test doesn't work. Here's what I've tried:
Followed the quick start for creating a node.js app.
Ran the app. Ensured it worked by sending an e-mail.
Modified the test Checking that the sample can send an email to use my account parameters.
Tried to run the test. It fails with 403: insufficient scope. The call to get the token returned scopes, but lacked Mail.Send.
In the post data for the call to login.microsoftonline.com, I added "scope: 'Mail.Send'"
I still receive a valid token, and the return scope includes Mail.Send, but when I try to post with that token, I get 400: cannot POST /beta/me/sendMail
I tried adding scope (Mail.Send) in the query string and as a header (thought I saw that somewhere), but it made no difference.
I added the Mail.Send permission (under "Application Permissions") for the app in the application registration portal.
I compared the token (using https://jwt.ms) from my test call to the call from the app when it works. I see no real difference. They both contain the Mail.Send scope.
Here is the code (which is only slightly different from what's in the sample):
// in graphHelper.js
function postSendMail(accessToken, message, callback) {
request
.post('https://graph.microsoft.com/beta/me/sendMail')
//.post('https://graph.microsoft.com/beta/me/sendMail?scope=Mail.Send') // nope
.send(message)
.set('Authorization', 'Bearer ' + accessToken)
.set('Content-Type', 'application/json')
.set('Content-Length', message.length)
.set('scope', 'Mail.Send') // nope
.end((err, res) => {
callback(err, res);
});
}
describe('Integration', function () { // mocha
var accessToken;
var scope;
const config = getConfig();
// My account variables in testConfig.json file
function getConfig() {
var configFilePath = path.join(__dirname, 'testConfig.json');
return JSON.parse(fs.readFileSync(configFilePath, { encoding: 'utf8' }));
}
function getAccessToken(done) {
var postData = querystring.stringify(
{
grant_type: 'password',
//grant_type: 'client_id', // not supported
//grant_type: 'authorization_code', // This assumes you've requested an auth code.
resource: 'https://graph.microsoft.com/',
scope: 'Mail.Send',
client_id: config.test_client_id_v2,
client_secret: config.test_client_secret_v2,
username: config.test_username,
password: config.test_password
}
);
var postOptions = {
host: 'login.microsoftonline.com',
port: 443,
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = https.request(postOptions, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
const response = JSON.parse(data);
accessToken = response.access_token;
scope = response.scope;
done();
});
});
postRequest.on('error', function (e) {
console.log('Error: ' + e.message);
done(e);
});
postRequest.write(postData);
postRequest.end();
}
before( // eslint-disable-line no-undef
function (done) {
getAccessToken(done);
}
);
it('Checking that the sample can send an email',
function (done) {
var postBody = emailer.generateMailBody(config.test_name, config.test_username);
graphHelper.postSendMail(
accessToken, scope,
JSON.stringify(postBody),
function (error) {
assert(error === null, `The sample failed to send an email: ${error}`);
done();
});
}
);
});

Fetch request on API Rails doesn't return json

In a Rails API, I have a login POST method in my UsersController which takes 2 parameters (mail and password) and check in DB if a record is found and if so returns it as JSON.
def login(mail, password)
mail, password = params.values_at(:mail, :password)
user = User.where(mail: mail, password: password)
render json: user
end
In my front side, in React, I call this method with fetch which takes the mail and password values in a form and expect to have the user as JSON in my 'res':
login = () => {
if(this.state.mail != null && this.state.password != null){
fetch('http://127.0.0.1:3001/api/login', {
method: 'post',
body: JSON.stringify({
mail: this.state.mail,
password: this.state.password
}),
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
}
})
.then((res) => {
console.log(res)
if(res.data.length === 1 ){
const cookies = new Cookies();
cookies.set('mercato-cookie',res.data[0].id,{path: '/'});
this.setState({redirect: true})
}
})
} bodyUsed: false
headers: Headers { }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://127.0.0.1:3001/api/login"
__proto__: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … } auth.js:32
}
Problem is my res doesn't correspond to what I return with render json: user, so I made a console.log(res) :
Response
bodyUsed: false
headers: Headers { }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://127.0.0.1:3001/api/login"
__proto__: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … } auth.js:32
I tried returning simple JSON text in case there was a problem with my user variable and also tried changing render json: user to format.json { render json: user } but with no result :/
I made the request on Postman and it returns the appropiate JSON, so i guess the problem comes from my fetch ?
Fetch's response doesn't automatically translate to JSON, you need to call response.json() (which returns a promise) in order to get the JSON value. See this example from MDN, or here's some ES6 to match your code:
fetch(myRequest)
.then(response => response.json())
.then((data) => {
// I'm assuming you'll have direct access to data instead of res.data here,
// depending on how your API is structured
if (data.length === 1) {
const cookies = new Cookies();
cookies.set('mercato-cookie', data[0].id, {path: '/'});
this.setState({redirect: true});
}
});

Fetch in ReactNative can not deliver the paras in body to the server

ReactNative provide me with fetch to send a httpRequest.The attribute of body includes my parameters which are to send to the server.But I can't get the parameters on my server.My codes are here:
fetch(`${keys.api}/login`,
{
method: 'POST',
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}
).then((response) => {
if(response._bodyText == 'success') {
this.props.resetToRoute({
name: '主页',
component: Main,
hideNavigationBar: true,
});
} else {
this.cancelLogin();
}
}).catch((error) => {
console.warn(error);
this.cancelLogin();
});
And the console in my J2EE Web Server prints the message:
The httpRequest message
There is no parameter in my httpRequest(In other words,The body can not deliver any parameters),I need help.
It's dangerous to show my username and password in the url.
i have met the problem twice on jetty-8.1 on different condition
first ,you should know that it has nothing to do with react-native
fetch put the data in body to header "payload" when the client made a request.i thought jetty-8.1 does not support get data from the payload header
,change the way
Getting request payload from POST request in Java servlet will be helpful
or maybe use the websockt or XMLhttpRequest object to send a request
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString()

Resources