Getting erorr Cannot POST /undefined/signup - javascript

I can sign up a user via postman. But when I use my app I am getting that error. My signup method is ok. But my fetch address is not good. here is method.
export const signup = user => {
return fetch(`${API}/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
};
const API = process.env.REACT_APP_API_URL;

Related

How to make a fetch request to TinyURL?

I am trying to make a fetch request specifically a post request to tinyURL to shortern a url generated on my site. here is the tinyURL API
Currently, I am writing my code like this but it doesn't appear to be returning the short url.
the word tinyurl seems to be banned within links so all links
containing the word tinyurl have been replaced with "SHORT"
here is the tinyURL API https://SHORT.com/app/dev
import * as React from 'react'
interface tinyURlProps { url: string } export const useTinyURL = ({ url }: tinyURlProps) => { React.useEffect(() => {
const apiURL = 'https://api.SHORT.com/create'
const data = JSON.stringify({ url: url, domain: 'tiny.one' })
const options = {
method: 'POST',
body: data,
headers: {
Authorization:
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
Accept: 'application/json',
'Content-Type': 'application/json',
},
} as RequestInit
fetch(apiURL, options)
.then((response) => console.log(response))
.then((error) => console.error(error))
console.log('TinyUrl ran') }, [url])
}
The snippet below seems to work
const qs = selector => document.querySelector(selector);
let body = {
url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
domain: `tiny.one`
}
fetch(`https://api.tinyurl.com/create`, {
method: `POST`,
headers: {
accept: `application/json`,
authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
'content-type': `application/json`,
},
body: JSON.stringify(body)
})
.then(response => {
if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
return response.json()
})
.then(data => {
qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
qs(`#link`).href = data.data.tiny_url;
qs(`#link`).innerText = data.data.tiny_url;
})
.catch(error => console.error(error));
body {
font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

Axios can't send credentials

I'm trying to include credentials to my requests
I'm using axios but axios don't send credentials with request.
This is how i do it with axios.
const axiosConfig = {
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
};
axios
.get("someurl" + data, axiosConfig)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
But when i try it with fetch everything work.
fetch("someurl" + data, {
credentials: "include"
})
.then(function(response) {
return response.json();
})
.then(result => {
console.log(result);
});
how make it work with axios too?
You should see the auth parameter inside the axios config object
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
see https://github.com/axios/axios

JavaScript Fetching Multiple Requests In An Order

I am trying to fetch multiple requests in an order in React. There are 3 requests,
first one gathering encoded information from backend
get token from authentication server
use api with the token.
All of them must be in order. But I am having difficulties because of async fetch function. I can't reach fetch's response outside of .then() block.
To solve it, I used await / async. But it caused another problem. My 3 requests must be in a sequencial order. When I use async, order gets broken.
Here is the code.
class App extends Component {
constructor() {
super();
this.state = { code: '', encoded: '', access_token: '', refresh_token: '' };
}
getCarDetails() {
const carId = '2F3A228F6F66AEA580'
var query = 'https://api.mercedes-benz.com/experimental/connectedvehicle/v1/vehicles/'.concat(carId).concat('/doors')
fetch(query, {
method: 'GET',
headers: {
'Authorization': 'Bearer '.concat(this.state.access_token),
'accept': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
}
getToken() {
var post_data = {
grant_type: 'authorization_code',
code: this.state.code,
redirect_uri: 'http://localhost'
}
fetch('https://api.secure.mercedes-benz.com/oidc10/auth/oauth/v2/token', {
method: 'POST',
headers: new Headers({
'Authorization': 'Basic '.concat(this.state.encoded),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: queryString.stringify(post_data)
})
.then(res => res.json())
.then(data => this.setState({ access_token: data.access_token, refresh_token: data.refresh_token }))
.catch(err => console.log(err));
}
getEncodedClientIdAndClientSecret() {
if (this.state.code != null) {
fetch('http://localhost:8000/encodeClientIdAndSecret', {
method: 'POST'
})
.then(res => res.json())
.then(data => this.setState({ encoded: data.encoded }))
.catch(err => console.log(err));
}
}
componentDidMount() {
const values = queryString.parse(this.props.location.search)
this.setState({ code: values.code })
console.log(this.state)
this.getEncodedClientIdAndClientSecret();
console.log(this.state) //this state is empty
//this.getToken();
//this.getCarDetails();
}
AWAIT / ASYNC
async getEncodedClientIdAndClientSecret() {
if (this.state.code != null) {
const response = await fetch('http://localhost:8000/encodeClientIdAndSecret', {
method: 'POST'
})
const data = await response.json();
console.log(data)
}
}
If I put await / async, I am having sequence problem between 3 requests.
in order to use async await on methods like
await getEncodedClientIdAndClientSecret();
await getToken();
you need to first return a promise from those functions like:
getToken() {
var post_data = {
grant_type: 'authorization_code',
code: this.state.code,
redirect_uri: 'http://localhost'
}
return fetch('https://api.secure.mercedes-benz.com/oidc10/auth/oauth/v2/token', {
method: 'POST',
headers: new Headers({
'Authorization': 'Basic '.concat(this.state.encoded),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: queryString.stringify(post_data)
})
.then(res => res.json())
.then(data => this.setState({ access_token: data.access_token, refresh_token: data.refresh_token }))
.catch(err => console.log(err));
}
so it can wait for the promise to finish, othewise they will run in parallel and finish in random order.

axios post method 400 bad request

I'm getting a JSON file, editing it and trying send it back to server. But when I use post method it throws an error 400 bad request.In response shows "no template_id or no template_json presented". What could be the problem?
saveData() {
const { data } = this.state
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
Please try to use this:
data.template_id = 1;
saveData() {
const { data } = this.state
data.template_id = 1;
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
You missed the parameter template_id, or you need to ask from your API developer to send the documentations of the POST Method API.

React Native "fetch" returning server response without the information

I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.

Categories

Resources