here is my javascript form handler
where i get data from the form to send it as request to API
import { Store } from './http/requests.js';
$(document).ready(function () {
$('#form_submit').submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
Store(formData);
});
});
js requests file handler
where i use customized post,get functions to send data with options that i provide on it
import { get, post } from '../helper.js';
let pageName = window.location.pathname;
pageName = pageName.slice(1, pageName.length - 5);
export const Store = (value) => {
switch (pageName) {
case 'add_car':
post('user/create_car', value, true, 'multipart/form-data')
.then((res) => {
console.log(res);
return res;
})
.catch((err) => console.log(err));
default:
break;
}
};
then the helper file where i use fetch get,post with option that i receive from "requests.js" file and provide it here
import { Local as loc } from './localStorage.js';
const API_URL = 'http://127.0.0.1:8000/api';
// token if exists in localStorage
const token = loc('get', 'token');
// POST Request
export const post = (
url,
formData,
auth = false,
type = 'application/json',
providedToken = token,
) => {
return fetch(`${API_URL}/${url}`, {
method: 'POST',
body: JSON.stringify(formData),
headers: {
'Content-Type': type,
Authorization: auth ? `Bearer ${providedToken}` : null,
},
})
.then((res) => res.json())
.then((res) => {
console.log(res);
return res;
})
.catch((err) => console.log(err));
};
and finally the Laravel API Cotroller where i tried to debug the issue
public function create_car(Request $request)
{
return (response()->json([
"files" => $_FILES,
"all Request data" => $request,
]));
}
the response i get when i send data from javascript to Laravel API
API gives me back this empty object as a response
it's seems like fetch has a problem ... anyway i just replaced fetch library with axios and everything runs perfectly
here is what i did on helper.js file
// POST Request
export const post = (
url,
formData,
auth = false,
type = 'application/json',
providedToken = token,
) => {
return axios({
method: 'POST',
url: `${API_URL}/${url}`,
data: formData,
headers: {
'Content-Type': type,
Authorization: auth ? `Bearer ${providedToken}` : null,
},
})
.then((res) => {
console.log(res);
return res.data;
})
.catch((err) => console.log(err.data));
};
Related
I create a login form using Nextjs and backend with Laravel 8, I generate an XSRF-TOKEN in Laravel then set it on cookie, I can see the token inside inspect element> application tab> cookie section, but I can't set it on my fetch request to make my login, I using redux to store my data such: products, auth, cart and etc
AuthAction.js code:
export const LOGIN_AUTH = "LOGIN_AUTH";
export const LOGOUT_AUTH = "LOGOUT_AUTH";
export const HandleLogin = (data) => {
return async (dispatch, getState) => {
const getCsrf = await fetch("http://localhost:8000/sanctum/csrf-cookie");
if (!getCsrf.ok) {
throw new Error("Faild to set csrf token");
}
console.log("getCsrf", cookie.load("XSRF-TOKEN"));
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw Error("Login faild");
}
try {
const responseData = await response.json();
console.log("login", responseData);
dispatch({
type: LOGIN_AUTH,
user: responseData,
});
} catch (err) {
console.log("Login err", err);
throw err;
}
};
};
after console.log("getCsrf", cookie.load("XSRF-TOKEN")); nothing happened.
what do I do wrong in my code?
cookie screenshot:
request response:
Use axios instead of fetch.
Example:
axios
.get("http://localhost:8000/sanctum/csrf-cookie", {
withCredentials: true,
})
.then((response) => {
axios("http://localhost:8000/api/app/user/login", {
method: "post",
data: data,
withCredentials: true,
})
.then((response) => {
console.log("login", response.data);
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
// handle error
console.log(error);
})
.then(() => {
//
});
Since your next.js and laravel apps are on different origins, you need to set fetch to explicitly send cookies.
const response = await fetch("http://localhost:8000/api/app/user/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
credentials: 'include'
});
You can read more about the credentials property in the MDN docs
Also, you can read the cookie in the front-end if it's http-only cookie.
Also, don't forget to set up Cross origin resource sharing in your backend app.
I am trying to make a POST request to an API server and I am sending an array of JSON, the problem is that I get this error:
cannot unmarshal array into Go value of type models.UserRequest
I tried to unmarshal it using a factory and then initializing the objects, but I still get this error, how can I fix this error and make my request? Here is my code:
import fetch from 'node-fetch';
import xlsx from 'xlsx';
const baseUrl = "";
const apiToken = "";
const accountId = "";
const wb = xlsx.readFile('users.xlsx');
const ws = wb.Sheets['users'];
const data = xlsx.utils.sheet_to_json(ws);
// console.log(data)
const options = {
method: "POST",
headers: {
Authorization: `Bearer ${apiToken}`,
"gtmhub-accountid": accountId,
"Content-type": "application/json; charset=UTF-8",
Accept: "application/json, text/plain, */*",
},
body: JSON.stringify(
data
),
};
const createUser = (url, settings) => {
return fetch(`${url}/users`, settings)
.then((response) => response.text())
.then((data) => console.log(data))
.catch((error) => {
console.log(error.message);
});
};
createUser(baseUrl, options);
You should be able, that you send right object structure to you api service. Also this seems like as the problem on the api service side
I've found this function to generate oauth-1.0a header:
// auth.js
const crypto = require("crypto");
const OAuth1a = require("oauth-1.0a");
function auth(request) {
const oauth = new OAuth1a({
consumer: {
key: process.env.TWITTER_API_KEY,
secret: process.env.TWITTER_API_SECRET_KEY,
},
signature_method: "HMAC-SHA1",
hash_function(baseString, key) {
return crypto.createHmac("sha1", key).update(baseString).digest("base64");
},
});
const authorization = oauth.authorize(request, {
key: process.env.TWITTER_ACCESS_TOKEN,
secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
});
return oauth.toHeader(authorization).Authorization;
}
module.exports = auth;
It works fine if I try it with Twitter API v1.1:
// v1.js
require("dotenv").config();
const axios = require("axios");
const auth = require("./auth");
const url = "https://api.twitter.com/1.1/favorites/create.json";
const method = "POST";
const params = new URLSearchParams({
id: "1397568983931392004",
});
axios
.post(url, undefined, {
params,
headers: {
authorization: auth({
method,
url: `${url}?${params}`,
}),
},
})
.then((data) => {
return console.log(data);
})
.catch((err) => {
if (err.response) {
return console.log(err.response);
}
console.log(err);
});
But if I try it with Twitter API v2:
// v2.js
require("dotenv").config();
const axios = require("axios");
const auth = require("./auth");
const url = `https://api.twitter.com/2/users/${process.env.TWITTER_USER_ID}/likes`;
const method = "POST";
const data = {
tweet_id: "1397568983931392004",
};
axios
.post(url, data, {
headers: {
authorization: auth({
method,
url,
data,
}),
},
})
.then((data) => {
return console.log(data);
})
.catch((err) => {
if (err.response) {
return console.log(err.response);
}
console.log(err);
});
it fails with:
{
title: 'Unauthorized',
type: 'about:blank',
status: 401,
detail: 'Unauthorized'
}
I tried encoding the body of the request as suggested here, but get the same error:
require("dotenv").config();
const axios = require("axios");
const auth = require("./auth");
const querystring = require("querystring");
const url = `https://api.twitter.com/2/users/${process.env.TWITTER_USER_ID}/likes`;
const method = "POST";
const data = percentEncode(
querystring.stringify({
tweet_id: "1397568983931392004",
})
);
function percentEncode(string) {
return string
.replace(/!/g, "%21")
.replace(/\*/g, "%2A")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29");
}
axios
.post(url, data, {
headers: {
"content-type": "application/json",
authorization: auth({
method,
url,
data,
}),
},
})
.then((data) => {
return console.log(data);
})
.catch((err) => {
if (err.response) {
return console.log(err.response);
}
console.log(err);
});
If tested with Postman, both endpoints (1.1 and 2) work fine with the same credentials.
Any ideas on what am I doing wrong while using v2 or how to get it working with Twitter API v2?
I suspect it's something related with the body of the request as that's the main diference between both requests, but haven't been able to make it work.
Figure it out, the body of the request should not be included while generating the authorization header:
require("dotenv").config();
const axios = require("axios");
const auth = require("./auth");
const url = `https://api.twitter.com/2/users/${process.env.TWITTER_USER_ID}/likes`;
const method = "POST";
const data = {
tweet_id: "1397568983931392004",
};
axios
.post(url, data, {
headers: {
authorization: auth({
method,
url,
}),
},
})
.then((data) => {
return console.log(data);
})
.catch((err) => {
if (err.response) {
return console.log(err.response);
}
console.log(err);
});
Basically, when making a post request to Twitter API v1.1, the data should be encoded, should be used to generate the authorization header, and the post request should be sent as application/x-www-form-urlencoded.
When making a post request to Twitter API v2, the data should not be encoded, should not be included while generating the authorization header, and must be sent as application/json.
Hope this becomes helpful to someone else.
$ajax server response:
{"username":"","password":""}
fetch server response:
{"{\"username\":\"\",\"password\":\"\"}":""}
Why aren't they the same? I need the same server response. I'm using PHP+Apache
Here is my code:
import $ from 'jquery';
export function FetchData(type, data){
const serverUrl = 'http://localhost/oms/'+ type + ".php";
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: serverUrl,
data //body : {username: "username", password:"password"}
})
.done(function(res) {
//console.log(res);
resolve (res);
})
.fail(function(jqXHR, exception){
//alert('server error()');
reject(jqXHR);
});
fetch(serverUrl,{
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/x-www-form-urlencoded',
//'Access-Control-Allow-Origin': '*',
//'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PUT,DELETE',
//'Access-Control-Allow-Headers': 'Content-Type,Accept',
},
body: JSON.stringify(data)
//body : {username: data.username, password: data.password}
})
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error) => {
reject(error);
});
});
}
The responses are essentially the same just that response from fetch library returns a Stringified JSON.
You need to convert it into actual JS object.
const responseData = JSON.parse(response.json())
This occurs because you're sending the content type application/x-www-form-urlencoded with JSON data you need to change it to application/json like
export const FetchData = (type, data) => {
let serverUrl = 'http://localhost/oms/'+ type + ".php";
let data = {
username: data.username,
password: data.password
};
return new Promise((resolve, reject) => {
fetch(serverUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: 'include',
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson)
})
.catch((error) => {
reject(error)
})
})
};
I added credentials it's read-only property of the Request interface indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. This is similar to XHR’s withCredentials flag
If you want to use something smaller to jQuery you can use Axios It's XMLHttpRequests
If you get some CORS issues this will help you
I'm trying to make a POST request with a GraphQL query, but it's returning the error Must provide query string, even though my request works in PostMan.
Here is how I have it running in PostMan:
And here is the code I'm running in my application:
const url = `http://localhost:3000/graphql`;
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
Any ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the fetch request is formatted as Text like I've specified in the PostMan request's body?
The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.
This should work in your case:
const url = `http://localhost:3000/graphql`;
const query = `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
return fetch(url, {
method: 'POST',
Header: {
'Content-Type': 'application/graphql'
}
body: query
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
This is how to submit GraphQL variables:
const query = `
query movies($first: Int!) {
allMovies(first: $first) {
title
}
}
`
const variables = {
first: 3
}
return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
return data
})
.catch((e) => {
console.log(e)
})
I created a complete example on GitHub.